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

70 lines
1.8 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;
using Microsoft.Extensions.DependencyInjection;
using System;
2023-08-15 17:21:04 +00:00
using System.Collections.Generic;
2023-06-18 02:56:22 +00:00
using System.IO;
using System.Threading.Tasks;
2023-06-17 13:32:39 +00:00
namespace BotSharp.Plugin.MetaAI.Providers;
public class fastTextEmbeddingProvider : ITextEmbedding
{
private FastTextWrapper _fastText;
private readonly IServiceProvider _services;
2023-06-17 13:32:39 +00:00
2023-06-26 23:08:24 +00:00
public int Dimension
{
get
{
2023-09-01 15:42:16 +00:00
LoadModel();
2023-06-26 23:08:24 +00:00
return _fastText.GetModelDimension();
}
}
2023-06-18 13:02:59 +00:00
public string Provider => "meta-ai";
public fastTextEmbeddingProvider(IServiceProvider services)
2023-06-17 13:32:39 +00:00
{
_services = services;
2023-06-26 23:08:24 +00:00
}
2023-06-18 02:56:22 +00:00
public Task<float[]> GetVectorAsync(string text)
2023-06-26 23:08:24 +00:00
{
2023-08-18 02:44:49 +00:00
LoadModel();
return Task.FromResult(_fastText.GetSentenceVector(text));
2023-06-17 13:32:39 +00:00
}
2023-08-15 17:21:04 +00:00
public async Task<List<float[]>> GetVectorsAsync(List<string> texts)
2023-08-15 17:21:04 +00:00
{
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(await GetVectorAsync(texts[i]));
2023-08-15 17:21:04 +00:00
}
return vectors;
}
2023-08-18 02:44:49 +00:00
private void LoadModel()
{
if (_fastText == null)
{
var settings = _services.CreateScope().ServiceProvider
.GetRequiredService<fastTextSetting>();
if (!File.Exists(settings.ModelPath))
2023-08-18 02:44:49 +00:00
{
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.");
2023-08-18 02:44:49 +00:00
}
_fastText = new FastTextWrapper();
if (!_fastText.IsModelReady())
{
_fastText.LoadModel(settings.ModelPath);
2023-08-18 02:44:49 +00:00
}
}
}
2023-06-17 13:32:39 +00:00
}