github ↗
docs menu

Module Brot.Normalizer

Text normalization.

Normalizers transform text before tokenization: lowercasing, accent removal, Unicode normalization, whitespace cleanup, and model-specific preprocessing. They are the first stage in the tokenization pipeline, applied before Pre_tokenizer and vocabulary-based encoding.

Compose normalizers with sequence:

ocaml
let n =
  Normalizer.sequence
    [ Normalizer.nfd; Normalizer.strip_accents; Normalizer.lowercase ]
in
Normalizer.apply n "Caf\u{00E9}"
(* "cafe" *)
#type t

The type for normalizers.

Normalizers

Unicode normalization

#val nfc : t

nfc is Unicode NFC normalization (canonical composition).

#val nfd : t

nfd is Unicode NFD normalization (canonical decomposition).

#val nfkc : t

nfkc is Unicode NFKC normalization (compatibility composition).

#val nfkd : t

nfkd is Unicode NFKD normalization (compatibility decomposition).

Text transforms

#val lowercase : t

lowercase is the full Unicode lowercase mapping. It is not case folding: "ß" and "fi" lowercase to themselves.

#val strip_accents : t

strip_accents removes every mark (Mn, Mc, Me). It does not decompose: compose it after nfd to also remove the accents of precomposed characters.

#val strip : ?left:bool -> ?right:bool -> unit -> t

strip ?left ?right () is a normalizer that strips Unicode whitespace from text boundaries. left and right default to true.

#val replace : pattern:string -> replacement:string -> t

replace ~pattern ~replacement is a normalizer that replaces every occurrence of the string pattern with replacement, scanning left to right without overlap. An empty pattern occurs before every character and at the end of the text. Empty text is returned unchanged.

#val replace_regex : pattern:string -> replacement:string -> t

replace_regex ~pattern ~replacement is a normalizer that replaces every match of the regular expression pattern with replacement. Matches are found left to right, leftmost first, without overlap; an empty match right after another match is skipped. Empty text is returned unchanged.

pattern is written in the dialect of tokenizer files: Unicode-aware, so that \s, \d and \w and their negations, . and negated classes stand for characters rather than bytes, and \p{..} selects a general category (L, Lu, Nd, ...) of Unicode 18.0.0 or a script (Han, Latin, ...) of Unicode 17.0.0. A character new in 18.0.0 has a category and no script, so the ideograph U+2B81E, new in 18.0.0, is in [\p{Lo}&&[^\p{Han}]] and Kimi K2's pattern takes it into its words. ^ and $ are line anchors, \A, \z and \Z text anchors. Groups, alternation, greedy and lazy quantifiers and bracket classes are supported, nested and intersected with && as in [\p{L}&&[^\p{Han}]], a leading ^ negating the whole intersection, as are the case-insensitive option ((?i), (?i:..)), under which a character or a bracket class stands for every character with the same simple case folding, and a lookahead ((?=..), or (?!..) over one character) that ends the pattern or one of its alternatives. A lookahead anywhere else, lookbehind, backreferences, atomic groups, word boundaries and possessive quantifiers are not.

Raises Invalid_argument if pattern is invalid or uses an unsupported construct; the message says which.

#val prepend : string -> t

prepend s is a normalizer that prepends s to non-empty text. Empty text is returned unchanged.

Byte-level encoding

#val byte_level : t

byte_level is GPT-2 style byte-level encoding: each byte of the text is mapped to a printable Unicode character using the GPT-2 byte-to-unicode table. A space, for instance, becomes U+0120.

Model-specific

#val nmt : t

nmt is the control character cleanup of neural machine translation models. It removes U+0001-U+0008, U+000B, U+000E-U+001F, U+007F, U+008F and U+009F, and replaces with a space the tab, line feed, form feed and carriage return, U+1680, U+200B-U+200F, U+2028, U+2029, U+2581, U+FEFF and U+FFFD.

#val precompiled : string -> t

precompiled charsmap is the normalizer of a SentencePiece model, as T5, ALBERT and XLNet ship it. charsmap is the model's precompiled_charsmap, as bytes: rules, each replacing a source string by another, compiled into a darts-clone double-array trie. Tokenizer files store it in base64, which of_json decodes.

The text is read one extended grapheme cluster at a time, as UAX #29 defines them at Unicode 17.0.0. A cluster of fewer than 6 bytes that starts with a rule's source becomes the replacement of the shortest such source, and the rest of the cluster is dropped. In any other cluster each character that is a rule's source becomes its replacement and the others are kept. A byte that does not start a valid UTF-8 character becomes U+FFFD.

In the alignment, a replacement stands for its source character by character, and the characters of a longer one past the source's length take the span of the source's last character. The rest of the source of a shorter one, like a removed character, belongs to no span. Characters removed before anything was written shift the spans of all that follows back by as many characters, and a removal right after a longer replacement gives its last character the span of the first character removed.

Raises Invalid_argument if charsmap is not a well-formed charsmap.

#val bert : ?clean_text:bool -> ?handle_chinese_chars:bool -> ?strip_accents:bool option -> ?lowercase:bool -> unit -> t

bert () is a BERT normalizer.

  • clean_text: remove control characters and normalize whitespace. Default: true.
  • handle_chinese_chars: pad CJK ideographs with spaces. Default: true.
  • strip_accents: decompose to NFD and remove the nonspacing marks. Unlike strip_accents, spacing and enclosing marks are kept, so that the vowel signs of abugidas survive. When None, accents are stripped iff lowercase is true. Default: None.
  • lowercase: apply the Unicode lowercase mapping. Default: true.

Composition

#val sequence : t list -> t

sequence ns is the composition of normalizers ns, applied left to right.

Applying

#val apply : t -> string -> string

apply n s is s normalized by n.

Alignment

Normalizing moves text around: nfd splits a character in two, strip_accents drops one, prepend adds one. An alignment records where the result came from, so that token offsets can be reported on the text the user passed in rather than on the normalized text.

#type alignment

The type for maps from the bytes of a normalized text back to the bytes of the text it was normalized from.

#val identity : string -> alignment

identity s is the alignment of s on itself, for text that was not normalized.

#val apply_aligned : t -> string -> string * alignment

apply_aligned n s is apply n s with its alignment on s.

#val original_span : alignment -> start:int -> stop:int -> int * int

original_span a ~start ~stop is the span of the original text that the normalized bytes [start;stop) come from: from the first byte the byte at start comes from to the last byte the byte at stop - 1 comes from.

Every byte of a character has the span of the whole character, so a span cutting a character short still reports it whole. A character the normalizer inserted has the span of the character it was inserted next to, and one it removed has no span at all, so the result can cover original bytes that no span reports. An empty start = stop gives an empty span.

Raises Invalid_argument unless 0 <= start <= stop <= n, where n is the length of the normalized text.

Formatting

#val pp : Stdlib.Format.formatter -> t -> unit

pp ppf n formats n for inspection.

Serialization

#val to_json : t -> Jsont.json

to_json n is n serialized to HuggingFace-compatible JSON.

#val of_json : Jsont.json -> (t, string) Stdlib.result

of_json json is a normalizer deserialized from HuggingFace JSON. Errors if json is not an object, has a missing or unknown "type" field, or has invalid parameters.