Ruby
litsea-ruby exposes Litsea to Ruby 3.1+ through magnus and rb-sys. It is published to RubyGems as litsea.
Installation
gem install litsea
The gem is source-only: gem install compiles the native extension from the bundled Rust source, which takes a minute or two. It needs:
- Ruby 3.1 or later, with the tools for building native gems (a C compiler and
make) - a Rust toolchain, 1.87 or later, installed with rustup
- libclang, which rb-sys uses to generate its Ruby bindings:
libclang-devon Debian and Ubuntu, the Xcode Command Line Tools on macOS
The gem compiles against the crates.io releases of litsea and litsea-binding-core of its own version, which it pins exactly, so Litsea.version always matches the gem version. It ships no Cargo.lock, so the other Rust dependencies resolve to their latest compatible releases at install time.
Note: The gems released from 0.13.0 until the fix for #247 fail to compile during installation (see the changelog).
gem install litseapicks the newest release, so this matters only when you pin one of those versions.
Getting a model
The gem contains no models. Download one from the models/ directory and pass its path — see Pre-trained Models. The model identifies its own kind, so has_pos? reports what was loaded and no flag is needed.
Segmentation
require "litsea"
seg = Litsea::Segmenter.open(:japanese, "models/japanese.model")
seg.segment("これはテストです。")
# => ["これ", "は", "テスト", "です", "。"]
The language accepts a Symbol or a String, and the ISO 639-1 code works too (:ja, "japanese").
For space-delimited languages the whitespace is returned as its own token, so the tokens always reconstruct the input:
Litsea::Segmenter.open(:korean, "models/korean.model").segment("안녕하세요 반갑습니다")
# => ["안녕하세요", " ", "반갑습니다"]
POS tagging
seg = Litsea::Segmenter.open(:japanese, "models/japanese_pos.model")
seg.segment_with_pos("これはテストです。").each do |token|
puts "#{token.surface}\t#{token.pos}\t[#{token.start}..#{token.end}]"
end
# これ PRON [0..6]
# は ADP [6..9]
# テスト NOUN [9..18]
# です AUX [18..24]
# 。 PUNCT [24..27]
start and end are byte offsets. Ruby’s String#[] counts characters, so slice with byteslice:
text.byteslice(token.start, token.end - token.start) # == token.surface
User dictionary
Every constructor accepts three keyword arguments (#263, #264): user_words:, an array of words to emit as single tokens wherever they occur; user_words_gate:, a flip ratio in 0.0–1.0 that applies a word only where the model’s margin against it is small enough; and user_word_tags:, a Hash mapping further words to the UPOS tag that segment_with_pos gives them (String keys and values).
seg = Litsea::Segmenter.open(:japanese, "models/japanese.model", user_words: ["雪だるま", "新幹線"])
seg.segment("雪だるまを作る")
# => ["雪だるま", "を", "作る"] (without the dictionary: ["雪", "だる", "ま", "を", "作る"])
With a POS model, user_word_tags: fixes the tag of a word the tagger gets wrong:
tagged = Litsea::Segmenter.open(:japanese, "models/japanese_pos.model", user_word_tags: { "チャットGPT" => "PROPN" })
tagged.segment_with_pos("チャットGPTに聞く").map { |t| "#{t.surface}/#{t.pos}" }
# => ["チャットGPT/PROPN", "に/ADP", "聞く/VERB"] (in user_words: instead: "チャットGPT/NOUN")
A registered word gets a boundary at each edge and none inside, overlapping occurrences are resolved leftmost-longest, and an untagged word of one character is ignored. With a POS model a word in user_words: is tagged like any other word (雪だるま/NOUN with japanese_pos.model), while a token that is a word in user_word_tags: gets its tag, ahead of the model’s lexicon and its tagger; segment ignores the tags. A word of one character in user_word_tags: changes no boundary and retags only the tokens that are exactly that character (issue #276). Matching is context-free, so a short fragment registered as a word breaks every other word it occurs in; user_words_gate: 0.0 applies a word only where the model already agrees with it. A gate outside 0.0–1.0, or a tag that is not one of the 17 UPOS tags (upper case), raises Litsea::InvalidArgumentError, and an unknown keyword raises ArgumentError. See Segmenter for the full semantics.
API
| Call | Returns |
|---|---|
Litsea::Segmenter.open(language, path, user_words: nil, user_words_gate: nil, user_word_tags: nil) | A segmenter |
Litsea::Segmenter.from_bytes(language, data, user_words: nil, user_words_gate: nil, user_word_tags: nil) | A segmenter (accepts a binary String) |
Litsea::Segmenter.from_uri(language, uri, user_words: nil, user_words_gate: nil, user_word_tags: nil) | A segmenter |
#language | String, the canonical language name |
#has_pos? | true or false |
#segment(text) | Array<String> |
#segment_batch(texts) | Array<Array<String>> |
#segment_tokens(text) | Array<Litsea::Token> with byte offsets |
#segment_with_pos(text) | Array<Litsea::Token> with tags and offsets |
#segment_with_pos_batch(texts) | Array<Array<Litsea::Token>> |
Litsea::Extractor.new(language)#extract(corpus_path, features_path, tsv: false, tag_free: false) | nil (tsv: reads the TSV corpus format; tag_free: omits the tag-dependent feature templates) |
Litsea::Extractor.new(language)#extract_two_stage(corpus_path, output_prefix, feature_set: "fast", tsv: false) | nil (writes {output_prefix}.stage1, .stage2 and .lexicon; feature_set: is "full", "balanced" or "fast") |
Litsea::Trainer.new(threshold, iterations, features)#train(model, cancel: nil) | BinaryMetrics |
Litsea::Trainer.new(...)#load_model(model_uri) | nil (continues training from an existing model: a path, file:// or http(s)://) |
Litsea::PerceptronTrainer.new(epochs, features)#train(model, cancel: nil) | MulticlassMetrics |
Litsea::TwoStageTrainer.new(epochs, prefix, dominance: 0.99)#train(model, cancel: nil) | TwoStageMetrics |
Litsea::TwoStageTrainer.new(...)#available? | false once train has run |
Litsea::CancelToken.new / #cancel / #reset / #cancelled? | A token / nil / nil / true or false |
Litsea.version | String, the litsea version |
Litsea.supported_languages | Array<String> |
Releasing the GVL
Long-running work — loading a model with open, from_uri or Trainer#load_model, extracting features, training, and the batch methods segment_batch and segment_with_pos_batch — runs with the Global VM Lock released, so other Ruby threads keep going. That is what makes cancellation useful:
cancel = Litsea::CancelToken.new
Thread.new { sleep 60; cancel.cancel }
metrics = Litsea::Trainer.new(0.01, 100_000, "features.txt").train("japanese.model", cancel: cancel)
Cancelling is not an error: training stops at its next check point, still writes the partially trained model, and returns its metrics. The binding never installs a signal handler.
Neither magnus nor rb-sys wraps rb_thread_call_without_gvl — magnus lists it among the C functions it does not bind, and it is declared in a header outside rb-sys’s generated bindings — so the binding declares it itself in src/gvl.rs, behind an extern "C" trampoline that catches panics so none can unwind across the C frame. Two tests hold that claim honest: one asserts another Ruby thread keeps ticking during training, and one asserts a cancel from another thread lands inside the training window. Removing the GVL release turns both red.
Segmentation of a single sentence keeps the GVL: it is short enough that releasing it would cost more than the work. from_bytes keeps it too, because it reads the bytes of the Ruby String in place.
A TwoStageTrainer can only be used once — training collapses stage 1 into an AdaBoost model, which consumes it. available? reports the state, and a second train raises.
Errors
Every error derives from Litsea::Error, so one rescue handles them all — the same hierarchy the Python and PHP bindings expose. A failure that fits none of the classes below is raised as Litsea::Error itself.
| Error | Raised when |
|---|---|
Litsea::InvalidArgumentError | Unknown language name, unknown feature set, reused trainer, user_words_gate: outside 0.0–1.0, a user_word_tags: value that is not a UPOS tag, dominance: outside (0.5, 1.0], an unknown URI scheme |
Litsea::ModelError | Download failed, or the file is a legacy joint POS model |
Litsea::IoError | A file could not be read or written |
Litsea::ParseError | The model or training data is malformed |
Litsea::UnsupportedError | The scheme or operation is unavailable in this build |
Litsea::PosUnavailableError | POS tagging requested from a segmentation-only model |
Development
make test-litsea-ruby # cargo test + rake compile + rake test
make lint-litsea-ruby # clippy + rubocop
make build-litsea-ruby # release build
make package-litsea-ruby # source gem into litsea-ruby/pkg/
make test-litsea-ruby-gem # gem install that gem in a clean container (needs Docker)
bundle must be usable with the active Ruby; a version manager’s shim can exist while the selected interpreter has no bundler, so the Makefile checks and says so. The parity tests build the litsea CLI and compare the binding’s output against it.
Build the gem with make package-litsea-ruby (bundle exec rake build), not gem build: the crate’s own Cargo.toml inherits from the Cargo workspace and only resolves inside this repository. The task builds the gem from the crate as cargo package normalizes it, and refuses to when the gem and crate versions differ or when litsea and litsea-binding-core are not pinned to that version. make test-litsea-ruby-gem installs the gem with gem install in a bare ruby:3.3 container and segments text with it. It compiles the litsea crates from the checkout, so it also works for versions that are not on crates.io yet.