UNPKG

shevchenko

Version:

JavaScript library for declension of Ukrainian anthroponyms

63 lines (60 loc) 2.31 kB
/** * @file JavaScript library for declension of Ukrainian anthroponyms * @module shevchenko * @version 3.2.2 * @author Oleksandr Tolochko <shevchenko-js@tooleks.com> * @license MIT * @copyright 2017-2026 Oleksandr Tolochko <shevchenko-js@tooleks.com> * @see {@link git+https://github.com/tooleks/shevchenko-js.git} */ import * as tf from '@tensorflow/tfjs'; import incorrectPredictionsCache from './cache/incorrect-predictions.json.js'; import { FamilyNameClassTransformer } from './family-name-class-transformer.js'; import { MODEL_INPUT_SIZE } from './model-config.js'; import { WordTransformer } from './word-transformer.js'; // Disable Node.js environment warning message in production code. // See https://github.com/tensorflow/tfjs/issues/5349 tf.env().set('IS_NODE', false); class FamilyNameClassifier { constructor(modelLoader) { this.modelLoader = modelLoader; this.modelPromise = null; this.wordTransformer = new WordTransformer(MODEL_INPUT_SIZE); this.familyNameClassTransformer = new FamilyNameClassTransformer(); } /** * Classifies the word class of a given family name. */ async classify(familyName) { let familyNameClass = this.getCached(familyName); if (familyNameClass != null) { return familyNameClass; } const model = await this.loadModel(); const input = this.wordTransformer.encode(familyName); const output = await model.predict(tf.tensor2d([input])).data(); familyNameClass = this.familyNameClassTransformer.decode(output); return familyNameClass; } /** * Returns a classified family name class from the cache if exists. */ getCached(familyName) { let familyNameClass = null; const wordClass = incorrectPredictionsCache[familyName.toLowerCase()]; if (wordClass) { familyNameClass = { wordClass }; } return familyNameClass; } /** * Loads the model from the storage. If called multiple times, resolves the same model instance. */ async loadModel() { if (this.modelPromise == null) { this.modelPromise = tf.loadLayersModel(this.modelLoader); } return this.modelPromise; } } export { FamilyNameClassifier };