Skip to content

Commit

Permalink
add emscripting bindings for Kiwi
Browse files Browse the repository at this point in the history
  • Loading branch information
RicBent committed Jun 13, 2024
1 parent 3f0eb0c commit 01eafe7
Showing 1 changed file with 48 additions and 1 deletion.
49 changes: 48 additions & 1 deletion bindings/wasm/kiwi_wasm.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,56 @@
#include <emscripten/val.h>
#include <emscripten/bind.h>

using namespace kiwi;


static Kiwi* kiwiInstance = nullptr;

void destroy() {
if (kiwiInstance) {
delete kiwiInstance;
kiwiInstance = nullptr;
}
}

void init(const std::string modelPath) {
destroy();

KiwiBuilder builder = KiwiBuilder{ modelPath, 0, BuildOption::default_, false };
kiwiInstance = new Kiwi(builder.build(DefaultTypoSet::withoutTypo));
}

std::vector<TokenInfo> analyze(const std::u16string text) {
if (!kiwiInstance) {
throw std::runtime_error("Not initialized");
}

const auto tokenResults = kiwiInstance->analyze(text, 1, Match::allWithNormalizing);
const auto tokenResult = tokenResults[0];

return tokenResult.first;
}

emscripten::val tokenInfoTagToString(const TokenInfo& tokenInfo) {
return emscripten::val(tagToString(tokenInfo.tag));
}


EMSCRIPTEN_BINDINGS(kiwi) {
emscripten::constant("VERSION_MAJOR", KIWI_VERSION_MAJOR);
emscripten::constant("VERSION_MINOR", KIWI_VERSION_MINOR);
emscripten::constant("VERSION_PATCH", KIWI_VERSION_PATCH);
emscripten::constant("VERSION", emscripten::val(KIWI_VERSION_STRING));
}

emscripten::function("init", &init);
emscripten::function("destroy", &destroy);
emscripten::function("analyze", &analyze);

emscripten::class_<TokenInfo>("TokenInfo")
.property("str", &TokenInfo::str)
.property("position", &TokenInfo::position)
.property("length", &TokenInfo::length)
.function("tagToString", &tokenInfoTagToString);

emscripten::register_vector<TokenInfo>("vector<TokenInfo>");
}

0 comments on commit 01eafe7

Please sign in to comment.