CoolFace
Apppublic

marconolimits/NMT

sourceHugging Faceupdated 4mo agoView on Hugging Face
1likes
UnityInterface.cpp46 linesDownload Raw Back to src
1#include "NMTWrapper.h"2#include <memory>3#include <string>4 5// Global instance to keep the model loaded in memory for Unity6std::unique_ptr<NMT::NMTWrapper> g_translator;7 8// Helper to store the last translated string in memory so Unity can read it9std::string g_last_translation;10 11extern "C" {12 13// 1. Initialize the CTranslate2 Model14// Unity will pass the path to the NLLB folder (e.g.,15// Application.streamingAssetsPath + "/nllb_int8")16__declspec(dllexport) void InitModel(const char *model_path) {17  if (!g_translator) {18    std::string path(model_path);19    std::string tokenizer_path = path + "/sentencepiece.bpe.model";20    g_translator = std::make_unique<NMT::NMTWrapper>(path, tokenizer_path);21  }22}23 24// 2. Translate Text25// Unity passes English text, and receives a pointer to the translated Italian26// string27__declspec(dllexport) const char *TranslateText(const char *input_text) {28  if (!g_translator) {29    return "Error: Model not initialized.";30  }31 32  std::string input(input_text);33 34  try {35    g_last_translation = g_translator->translate(input);36    return g_last_translation.c_str();37  } catch (const std::exception &e) {38    g_last_translation = std::string("Error during translation: ") + e.what();39    return g_last_translation.c_str();40  }41}42 43// 3. Free resources when the Unity App closes44__declspec(dllexport) void CleanupModel() { g_translator.reset(); }45}46