BotSharp/src/Plugins/BotSharp.Plugin.MetaAI/Providers/fastTextEmbeddingProvider.cs

67 lines
1.6 KiB
C#
Raw Normal View History

2023-06-17 13:32:39 +00:00
using BotSharp.Abstraction.MLTasks;
using BotSharp.Plugin.MetaAI.Settings;
using FastText.NetWrapper;
2023-08-15 17:21:04 +00:00
using System.Collections.Generic;
2023-06-18 02:56:22 +00:00
using System.IO;
2023-06-17 13:32:39 +00:00
namespace BotSharp.Plugin.MetaAI.Providers;
public class fastTextEmbeddingProvider : ITextEmbedding
{
private FastTextWrapper _fastText;
private readonly fastTextSetting _settings;
2023-06-26 23:08:24 +00:00
public int Dimension
{
get
{
if (!_fastText.IsModelReady())
{
_fastText.LoadModel(_settings.ModelPath);
}
return _fastText.GetModelDimension();
}
}
2023-06-18 13:02:59 +00:00
2023-06-17 13:32:39 +00:00
public fastTextEmbeddingProvider(fastTextSetting settings)
{
_settings = settings;
2023-06-26 23:08:24 +00:00
}
2023-06-18 02:56:22 +00:00
2023-06-26 23:08:24 +00:00
public float[] GetVector(string text)
{
2023-08-18 02:44:49 +00:00
LoadModel();
2023-06-17 13:32:39 +00:00
return _fastText.GetSentenceVector(text);
}
2023-08-15 17:21:04 +00:00
public List<float[]> GetVectors(List<string> texts)
{
2023-08-18 02:44:49 +00:00
LoadModel();
2023-08-15 17:21:04 +00:00
var vectors = new List<float[]>();
for (int i = 0; i < texts.Count; i++)
{
vectors.Add(GetVector(texts[i]));
}
return vectors;
}
2023-08-18 02:44:49 +00:00
private void LoadModel()
{
if (_fastText == null)
{
if (!File.Exists(_settings.ModelPath))
{
throw new FileNotFoundException($"Can't load pre-trained word vectors from {_settings.ModelPath}.\n Try to download from https://fasttext.cc/docs/en/english-vectors.html.");
}
_fastText = new FastTextWrapper();
if (!_fastText.IsModelReady())
{
_fastText.LoadModel(_settings.ModelPath);
}
}
}
2023-06-17 13:32:39 +00:00
}