|
| 1 | +#include <libpostal/libpostal.h> |
| 2 | +#include <nan.h> |
| 3 | +#include <string.h> |
| 4 | + |
| 5 | +void LanguageClassifier(const Nan::FunctionCallbackInfo<v8::Value>& info) { |
| 6 | + v8::Isolate *isolate = info.GetIsolate(); |
| 7 | + |
| 8 | + if (info.Length() < 1) { |
| 9 | + Nan::ThrowTypeError("Usage: language_classifier(text)"); |
| 10 | + return; |
| 11 | + } |
| 12 | + |
| 13 | + if (!info[0]->IsString()) { |
| 14 | + Nan::ThrowTypeError("First argument must be a string"); |
| 15 | + return; |
| 16 | + } |
| 17 | + |
| 18 | + Nan::Utf8String text_utf8(info[0]); |
| 19 | + char *text = *text_utf8; |
| 20 | + |
| 21 | + if (text == NULL) { |
| 22 | + Nan::ThrowTypeError("Could not convert first argument to string"); |
| 23 | + return; |
| 24 | + } |
| 25 | + |
| 26 | + libpostal_language_classifier_response_t *response = libpostal_classify_language(text); |
| 27 | + |
| 28 | + if (response != NULL) { |
| 29 | + v8::Local<v8::Array> lang_array = Nan::New<v8::Array>(response->num_languages); |
| 30 | + for (size_t i = 0; i < response->num_languages; i++) { |
| 31 | + const char* language = response->languages[i]; // Directly access the array |
| 32 | + |
| 33 | + v8::Local<v8::Object> lang_obj = Nan::New<v8::Object>(); |
| 34 | + Nan::Set(lang_obj, Nan::New("language").ToLocalChecked(), Nan::New(language).ToLocalChecked()); |
| 35 | + |
| 36 | + Nan::Set(lang_array, i, lang_obj); |
| 37 | + } |
| 38 | + libpostal_language_classifier_response_destroy(response); |
| 39 | + info.GetReturnValue().Set(lang_array); |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +void cleanup(void*) { |
| 44 | + libpostal_teardown(); |
| 45 | + libpostal_teardown_language_classifier(); |
| 46 | +} |
| 47 | + |
| 48 | +void init(v8::Local<v8::Object> exports) { |
| 49 | + if (!libpostal_setup() || !libpostal_setup_language_classifier()) { |
| 50 | + Nan::ThrowError("Could not load libpostal"); |
| 51 | + return; |
| 52 | + } |
| 53 | + |
| 54 | + v8::Local<v8::Context> context = exports->CreationContext(); |
| 55 | + |
| 56 | + exports->Set( |
| 57 | + context, |
| 58 | + Nan::New("language_classifier").ToLocalChecked(), |
| 59 | + Nan::New<v8::FunctionTemplate>(LanguageClassifier)->GetFunction(context).ToLocalChecked() |
| 60 | + ); |
| 61 | + |
| 62 | + #if NODE_MAJOR_VERSION >= 12 |
| 63 | + node::Environment* env = node::GetCurrentEnvironment(Nan::GetCurrentContext()); |
| 64 | + node::AtExit(env, cleanup, NULL); |
| 65 | + #else |
| 66 | + node::AtExit(cleanup); |
| 67 | + #endif |
| 68 | +} |
| 69 | + |
| 70 | +NODE_MODULE(language_classifier, init) |
0 commit comments