text-normalizer-jp 0.1.0

Japanese text normalization: width, kana, spaces, symbols, kanji numerals, neologdn-compatible preset. Zero dependencies, no regex, no panics. Preprocessing for Lindera / Vibrato / sudachi.rs.
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
#![cfg_attr(docsrs, feature(doc_cfg))]
#![warn(missing_docs)]

//! Japanese text normalization — the [neologdn](https://github.com/ikegami-yukino/neologdn)
//! position (pre-tokenizer cleaning) for Rust.
//!
//! Zero dependencies, no regex, no panic paths. Designed as the first stage of
//! an NLP pipeline, in front of tokenizers such as Lindera / Vibrato /
//! sudachi.rs: cleaning → normalization → masking, then hand off to
//! morphological analysis.
//!
//! # Quick start
//!
//! Build a [`Normalizer`] from the ops you need — they run in the order you
//! declare them — then call [`apply`]:
//!
//! ```
//! use text_normalizer_jp::Normalizer;
//!
//! let n = Normalizer::new()
//!     .kana_fullwidth()   // ガギ → ガギ
//!     .ascii_halfwidth()  // 123ABC → 123ABC
//!     .space_unify()
//!     .space_collapse();
//! assert_eq!(n.apply("123ABC ガギ"), "123ABC ガギ");
//! ```
//!
//! A pipeline is built once and applied many times; it is `Clone` and immutable
//! after construction. Or start from a [`preset`] and keep chaining:
//!
//! ```
//! use text_normalizer_jp::preset;
//!
//! let n = preset::neologdn().repeat_suppress(1);
//! assert_eq!(n.apply("PRML  副 読 本"), "PRML副読本");
//! ```
//!
//! # Choosing ops
//!
//! | Goal | Ops |
//! |---|---|
//! | Width folding | [`ascii_halfwidth`], [`digits_halfwidth`], [`kana_fullwidth`] |
//! | Spaces / newlines | [`space_unify`], [`space_collapse`], [`newline_unify`], [`newline_collapse`], [`newline_collapse_all`], [`trim_lines`], [`ja_space_remove`], [`ja_space_remove_aggressive`] |
//! | Symbols | [`hyphen_unify`], [`wave_dash_unify`], [`tilde_remove`], [`prolonged_sound_unify`], [`prolonged_sound_collapse`], [`repeat_suppress`] |
//! | Numbers | [`kanji_numeral_to_arabic`], [`digit_comma_remove`] |
//! | Cleaning | [`invisible_remove`], [`ascii_lowercase`] |
//! | User dictionary | [`with_replacements`] |
//!
//! **Order matters.** Two rules cover most pitfalls:
//!
//! - Run [`hyphen_unify`] and tilde handling *before* [`ascii_halfwidth`]:
//!   `-` (U+FF0D) and `~` (U+FF5E) must be classified as dash / tilde while
//!   they are still fullwidth.
//! - Run [`kana_fullwidth`] early, so ops that look at kana context
//!   ([`hyphen_unify`], [`ja_space_remove`]) see composed fullwidth kana.
//!
//! # Direct functions
//!
//! Every op is also a plain `fn(&str) -> String` in a submodule — [`width`],
//! [`space`], [`symbol`], [`number`], [`clean`] — usable without the builder:
//!
//! ```
//! assert_eq!(text_normalizer_jp::number::kanji_numeral_to_arabic("二十三"), "23");
//! ```
//!
//! # Feature flags (off by default)
//!
//! - `html` — module `html`: `html_detect` / `html_strip`. Complete-tag
//!   detection, entity decoding, `<script>`/`<style>` contents dropped.
//! - `mask` — module `mask`: URL / e-mail / `@mention` / `#hashtag` / phone
//!   masking for corpus cleaning — not NER-grade PII masking.
//!
//! # neologdn compatibility
//!
//! [`preset::neologdn`] targets neologdn 0.5.6 and passes the upstream test
//! suite, ported in full. Intentional divergences are listed on the preset and
//! explained in
//! [NEOLOGDN_COMPAT.md](https://github.com/uiuifree/rust-text-normalizer-jp/blob/main/NEOLOGDN_COMPAT.md).
//!
//! # Non-goals
//!
//! Romaji ⇔ kana transliteration, anything that needs morphological analysis
//! (reading estimation, place-name protection), sentence splitting, NER-based
//! PII masking, old kanji / IVS conversion (see the
//! [yosina](https://crates.io/crates/yosina) crate), and full Unicode NFC/NFD
//! (see [unicode-normalization](https://crates.io/crates/unicode-normalization)).
//!
//! [`apply`]: Normalizer::apply
//! [`ascii_halfwidth`]: Normalizer::ascii_halfwidth
//! [`digits_halfwidth`]: Normalizer::digits_halfwidth
//! [`kana_fullwidth`]: Normalizer::kana_fullwidth
//! [`space_unify`]: Normalizer::space_unify
//! [`space_collapse`]: Normalizer::space_collapse
//! [`newline_unify`]: Normalizer::newline_unify
//! [`newline_collapse`]: Normalizer::newline_collapse
//! [`newline_collapse_all`]: Normalizer::newline_collapse_all
//! [`trim_lines`]: Normalizer::trim_lines
//! [`ja_space_remove`]: Normalizer::ja_space_remove
//! [`ja_space_remove_aggressive`]: Normalizer::ja_space_remove_aggressive
//! [`hyphen_unify`]: Normalizer::hyphen_unify
//! [`wave_dash_unify`]: Normalizer::wave_dash_unify
//! [`tilde_remove`]: Normalizer::tilde_remove
//! [`prolonged_sound_unify`]: Normalizer::prolonged_sound_unify
//! [`prolonged_sound_collapse`]: Normalizer::prolonged_sound_collapse
//! [`repeat_suppress`]: Normalizer::repeat_suppress
//! [`kanji_numeral_to_arabic`]: Normalizer::kanji_numeral_to_arabic
//! [`digit_comma_remove`]: Normalizer::digit_comma_remove
//! [`invisible_remove`]: Normalizer::invisible_remove
//! [`ascii_lowercase`]: Normalizer::ascii_lowercase
//! [`with_replacements`]: Normalizer::with_replacements

pub mod clean;
pub mod number;
pub mod preset;
pub mod space;
pub mod symbol;
pub mod width;

#[cfg(feature = "html")]
pub mod html;
#[cfg(feature = "mask")]
pub mod mask;

/// A single normalization step. Held internally by [`Normalizer`].
#[derive(Debug, Clone)]
enum Op {
    AsciiHalfwidth,
    DigitsHalfwidth,
    KanaFullwidth,
    SpaceUnify,
    SpaceCollapse,
    NewlineUnify,
    NewlineCollapse { keep_paragraph: bool },
    TrimLines,
    /// Remove spaces adjacent to Japanese characters.
    /// `keep_latin_boundary: true` removes only between two Japanese chars
    /// (`検索 エンジン` → `検索エンジン`, `Rust 入門` kept).
    /// `false` is the neologdn-compatible behavior: a space is removed when
    /// at least one side is Japanese (`PRML 副読本` → `PRML副読本`).
    JaSpaceRemove { keep_latin_boundary: bool },
    HyphenUnify,
    WaveDashUnify,
    TildeRemove,
    ProlongedSoundUnify,
    ProlongedSoundCollapse,
    RepeatSuppress { max: usize },
    DigitCommaRemove,
    KanjiNumeralToArabic,
    InvisibleRemove,
    AsciiLowercase,
    Replacements(Vec<(String, String)>),
    #[cfg(feature = "html")]
    HtmlStrip,
    #[cfg(feature = "mask")]
    UrlMask(Option<String>),
    #[cfg(feature = "mask")]
    EmailMask(String),
    #[cfg(feature = "mask")]
    MentionRemove,
    #[cfg(feature = "mask")]
    HashtagRemove,
    #[cfg(feature = "mask")]
    PhoneMask(String),
}

/// Composable normalization pipeline. Build with the fluent methods, run with
/// [`Normalizer::apply`]. Ops execute in insertion order.
///
/// ```
/// use text_normalizer_jp::Normalizer;
///
/// let n = Normalizer::new().ascii_halfwidth().space_collapse();
/// assert_eq!(n.apply("Rust  入門"), "Rust 入門");
/// ```
#[derive(Debug, Clone, Default)]
pub struct Normalizer {
    ops: Vec<Op>,
}

impl Normalizer {
    /// Empty pipeline — [`apply`](Self::apply) returns input unchanged until
    /// ops are added with the builder methods.
    pub fn new() -> Self {
        Self { ops: Vec::new() }
    }

    fn push(mut self, op: Op) -> Self {
        self.ops.push(op);
        self
    }

    /// Fullwidth ASCII (U+FF01–U+FF5E) → halfwidth.
    /// Note: `~` (U+FF5E) becomes `~`; run [`Self::wave_dash_unify`] or
    /// [`Self::tilde_remove`] first if you want different tilde handling.
    ///
    /// ```
    /// use text_normalizer_jp::Normalizer;
    ///
    /// let n = Normalizer::new().ascii_halfwidth();
    /// assert_eq!(n.apply("123ABC()"), "123ABC()");
    /// ```
    pub fn ascii_halfwidth(self) -> Self {
        self.push(Op::AsciiHalfwidth)
    }

    /// Fullwidth digits only (U+FF10–U+FF19) → halfwidth. `123` → `123`.
    pub fn digits_halfwidth(self) -> Self {
        self.push(Op::DigitsHalfwidth)
    }

    /// Halfwidth katakana → fullwidth, composing dakuten/handakuten. Fullwidth
    /// and combining marks compose with any kana base too — see
    /// [`width::kana_fullwidth`].
    ///
    /// ```
    /// use text_normalizer_jp::Normalizer;
    ///
    /// let n = Normalizer::new().kana_fullwidth();
    /// assert_eq!(n.apply("ガギヴ"), "ガギヴ");
    /// assert_eq!(n.apply("う゛"), "ゔ");
    /// ```
    pub fn kana_fullwidth(self) -> Self {
        self.push(Op::KanaFullwidth)
    }

    /// Ideographic space (U+3000) and tab → single halfwidth space.
    pub fn space_unify(self) -> Self {
        self.push(Op::SpaceUnify)
    }

    /// Runs of spaces/tabs/ideographic spaces → one halfwidth space.
    pub fn space_collapse(self) -> Self {
        self.push(Op::SpaceCollapse)
    }

    /// CRLF / CR → LF.
    pub fn newline_unify(self) -> Self {
        self.push(Op::NewlineUnify)
    }

    /// Runs of 3+ newlines → 2 (paragraphs kept). `newline_collapse_all` for runs → 1.
    pub fn newline_collapse(self) -> Self {
        self.push(Op::NewlineCollapse { keep_paragraph: true })
    }

    /// Any run of newlines → a single newline.
    pub fn newline_collapse_all(self) -> Self {
        self.push(Op::NewlineCollapse { keep_paragraph: false })
    }

    /// Strip leading/trailing spaces, tabs and ideographic spaces on every line.
    pub fn trim_lines(self) -> Self {
        self.push(Op::TrimLines)
    }

    /// Remove spaces between two Japanese characters; a Latin boundary keeps
    /// its space.
    ///
    /// ```
    /// use text_normalizer_jp::Normalizer;
    ///
    /// let n = Normalizer::new().ja_space_remove();
    /// assert_eq!(n.apply("検索 エンジン"), "検索エンジン");
    /// assert_eq!(n.apply("Rust 入門"), "Rust 入門");
    /// ```
    pub fn ja_space_remove(self) -> Self {
        self.push(Op::JaSpaceRemove { keep_latin_boundary: true })
    }

    /// neologdn-compatible aggressive variant: remove a space when at least one
    /// side is Japanese. Includes the neologdn quirks documented on
    /// [`space::ja_space_remove`].
    ///
    /// ```
    /// use text_normalizer_jp::Normalizer;
    ///
    /// let n = Normalizer::new().ja_space_remove_aggressive();
    /// assert_eq!(n.apply("PRML 副読本"), "PRML副読本");
    /// assert_eq!(n.apply("Coding the Matrix"), "Coding the Matrix");
    /// ```
    pub fn ja_space_remove_aggressive(self) -> Self {
        self.push(Op::JaSpaceRemove { keep_latin_boundary: false })
    }

    /// Dash-like chars: after kana → `ー`; otherwise hyphen-shaped
    /// (`˗ ֊ ‐ ‑ ‒ – ⁃ ⁻ ₋ −`) → `-` and choonpu-shaped (`﹣ - ー — ― ─ ━`)
    /// → `ー`, with neologdn-style run collapsing. See [`symbol::hyphen_unify`].
    ///
    /// ```
    /// use text_normalizer_jp::Normalizer;
    ///
    /// let n = Normalizer::new().hyphen_unify();
    /// assert_eq!(n.apply("ス\u{2212}パ\u{2212}"), "スーパー"); // kana context → ー
    /// assert_eq!(n.apply("03\u{2212}1234"), "03-1234");        // elsewhere → -
    /// ```
    pub fn hyphen_unify(self) -> Self {
        self.push(Op::HyphenUnify)
    }

    /// Tilde-like chars (~ ~ ∼ ∾ 〰) → `〜` (neologdn `tilde='normalize_zenkaku'`).
    /// Mutually exclusive in spirit with [`Self::tilde_remove`]; pick one.
    pub fn wave_dash_unify(self) -> Self {
        self.push(Op::WaveDashUnify)
    }

    /// Remove tilde-like chars (~ 〜 ~ ∼ ∾ 〰) — the neologdn behavior.
    pub fn tilde_remove(self) -> Self {
        self.push(Op::TildeRemove)
    }

    /// Prolonged-sound-like chars (ー ˗) → `ー`. Runs before collapse.
    pub fn prolonged_sound_unify(self) -> Self {
        self.push(Op::ProlongedSoundUnify)
    }

    /// Runs of `ー` → one `ー`. `スーーパーー` → `スーパー`.
    pub fn prolonged_sound_collapse(self) -> Self {
        self.push(Op::ProlongedSoundCollapse)
    }

    /// Suppress repeated substrings to at most `max` consecutive occurrences —
    /// neologdn's `repeat` behavior, including multi-char units. Substring
    /// length is capped at 8 chars (neologdn default); use
    /// [`symbol::shorten_repeat`] directly for other caps. `max == 0` is a
    /// no-op.
    ///
    /// ```
    /// use text_normalizer_jp::Normalizer;
    ///
    /// let n = Normalizer::new().repeat_suppress(2);
    /// assert_eq!(n.apply("かわいいいいい"), "かわいい");
    ///
    /// let n = Normalizer::new().repeat_suppress(1);
    /// assert_eq!(n.apply("無駄無駄無駄無駄ァ"), "無駄ァ");
    /// ```
    pub fn repeat_suppress(self, max: usize) -> Self {
        self.push(Op::RepeatSuppress { max })
    }

    /// Remove `,` / `,` between ASCII digits. `1,234` → `1234`.
    pub fn digit_comma_remove(self) -> Self {
        self.push(Op::DigitCommaRemove)
    }

    /// Place-value kanji numerals → Arabic. Applies everywhere it matches —
    /// where to apply it (address fields etc.) is the caller's responsibility:
    /// place names are not protected (`四日市` → `4日市`).
    ///
    /// ```
    /// use text_normalizer_jp::Normalizer;
    ///
    /// let n = Normalizer::new().kanji_numeral_to_arabic();
    /// assert_eq!(n.apply("第三章の十五ページ"), "第3章の15ページ");
    /// assert_eq!(n.apply("一万二千"), "12000");
    /// assert_eq!(n.apply("二〇二五年"), "2025年");
    /// ```
    pub fn kanji_numeral_to_arabic(self) -> Self {
        self.push(Op::KanjiNumeralToArabic)
    }

    /// Remove zero-width chars, BOM, variation selectors, soft hyphen and
    /// C0/C1 controls (keeps `\n` and `\t`); NBSP → space.
    pub fn invisible_remove(self) -> Self {
        self.push(Op::InvisibleRemove)
    }

    /// ASCII A–Z → a–z. Non-ASCII untouched.
    pub fn ascii_lowercase(self) -> Self {
        self.push(Op::AsciiLowercase)
    }

    /// User dictionary: apply `(from, to)` pairs in declaration order.
    /// Domain rules belong here, not in the core.
    ///
    /// ```
    /// use text_normalizer_jp::Normalizer;
    ///
    /// let n = Normalizer::new().with_replacements(&[("株式会会社", "株式会社")]);
    /// assert_eq!(n.apply("株式会会社ロクゼロ"), "株式会社ロクゼロ");
    /// ```
    pub fn with_replacements(self, pairs: &[(&str, &str)]) -> Self {
        self.push(Op::Replacements(
            pairs
                .iter()
                .map(|(f, t)| ((*f).to_string(), (*t).to_string()))
                .collect(),
        ))
    }

    /// Strip HTML tags and decode entities. See [`html::html_strip`].
    #[cfg(feature = "html")]
    pub fn html_strip(self) -> Self {
        self.push(Op::HtmlStrip)
    }

    /// Replace URLs with `placeholder`, or remove them when `None`.
    #[cfg(feature = "mask")]
    pub fn url_mask(self, placeholder: Option<&str>) -> Self {
        self.push(Op::UrlMask(placeholder.map(str::to_string)))
    }

    /// Replace e-mail addresses with `placeholder`.
    #[cfg(feature = "mask")]
    pub fn email_mask(self, placeholder: &str) -> Self {
        self.push(Op::EmailMask(placeholder.to_string()))
    }

    /// Remove `@mention` tokens.
    #[cfg(feature = "mask")]
    pub fn mention_remove(self) -> Self {
        self.push(Op::MentionRemove)
    }

    /// Remove `#hashtag` tokens.
    #[cfg(feature = "mask")]
    pub fn hashtag_remove(self) -> Self {
        self.push(Op::HashtagRemove)
    }

    /// Replace phone-number-shaped digit runs with `placeholder`.
    #[cfg(feature = "mask")]
    pub fn phone_mask(self, placeholder: &str) -> Self {
        self.push(Op::PhoneMask(placeholder.to_string()))
    }

    /// Run the pipeline over `input`, applying ops in the order they were
    /// added. Never panics; an empty pipeline returns the input unchanged.
    pub fn apply(&self, input: &str) -> String {
        let mut s = input.to_string();
        for op in &self.ops {
            s = match op {
                Op::AsciiHalfwidth => width::ascii_halfwidth(&s),
                Op::DigitsHalfwidth => width::digits_halfwidth(&s),
                Op::KanaFullwidth => width::kana_fullwidth(&s),
                Op::SpaceUnify => space::space_unify(&s),
                Op::SpaceCollapse => space::space_collapse(&s),
                Op::NewlineUnify => space::newline_unify(&s),
                Op::NewlineCollapse { keep_paragraph } => {
                    space::newline_collapse(&s, *keep_paragraph)
                }
                Op::TrimLines => space::trim_lines(&s),
                Op::JaSpaceRemove { keep_latin_boundary } => {
                    space::ja_space_remove(&s, *keep_latin_boundary)
                }
                Op::HyphenUnify => symbol::hyphen_unify(&s),
                Op::WaveDashUnify => symbol::wave_dash_unify(&s),
                Op::TildeRemove => symbol::tilde_remove(&s),
                Op::ProlongedSoundUnify => symbol::prolonged_sound_unify(&s),
                Op::ProlongedSoundCollapse => symbol::prolonged_sound_collapse(&s),
                Op::RepeatSuppress { max } => symbol::repeat_suppress(&s, *max),
                Op::DigitCommaRemove => number::digit_comma_remove(&s),
                Op::KanjiNumeralToArabic => number::kanji_numeral_to_arabic(&s),
                Op::InvisibleRemove => clean::invisible_remove(&s),
                Op::AsciiLowercase => clean::ascii_lowercase(&s),
                Op::Replacements(pairs) => {
                    let mut t = s;
                    for (from, to) in pairs {
                        t = t.replace(from.as_str(), to);
                    }
                    t
                }
                #[cfg(feature = "html")]
                Op::HtmlStrip => html::html_strip(&s),
                #[cfg(feature = "mask")]
                Op::UrlMask(p) => mask::url_mask(&s, p.as_deref()),
                #[cfg(feature = "mask")]
                Op::EmailMask(p) => mask::email_mask(&s, p),
                #[cfg(feature = "mask")]
                Op::MentionRemove => mask::mention_remove(&s),
                #[cfg(feature = "mask")]
                Op::HashtagRemove => mask::hashtag_remove(&s),
                #[cfg(feature = "mask")]
                Op::PhoneMask(p) => mask::phone_mask(&s, p),
            };
        }
        s
    }
}