2023-06-17 13:32:39 +00:00
using BotSharp.Abstraction.MLTasks ;
using BotSharp.Plugin.MetaAI.Settings ;
using FastText.NetWrapper ;
2024-01-15 19:15:18 +00:00
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 ;
2023-11-16 13:37:53 +00:00
using System.Threading.Tasks ;
2023-06-17 13:32:39 +00:00
namespace BotSharp.Plugin.MetaAI.Providers ;
public class fastTextEmbeddingProvider : ITextEmbedding
{
private FastTextWrapper _fastText ;
2024-01-15 19:15:18 +00:00
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
2024-01-16 17:38:45 +00:00
public string Provider = > "meta-ai" ;
2024-01-15 19:15:18 +00:00
public fastTextEmbeddingProvider ( IServiceProvider services )
2023-06-17 13:32:39 +00:00
{
2024-01-15 19:15:18 +00:00
_services = services ;
2023-06-26 23:08:24 +00:00
}
2023-06-18 02:56:22 +00:00
2023-11-16 13:37:53 +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 ( ) ;
2023-11-16 13:37:53 +00:00
return Task . FromResult ( _fastText . GetSentenceVector ( text ) ) ;
2023-06-17 13:32:39 +00:00
}
2023-08-15 17:21:04 +00:00
2023-11-16 13:37:53 +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 + + )
{
2023-11-16 13:37:53 +00:00
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 )
{
2024-01-15 19:15:18 +00:00
var settings = _services . CreateScope ( ) . ServiceProvider
. GetRequiredService < fastTextSetting > ( ) ;
if ( ! File . Exists ( settings . ModelPath ) )
2023-08-18 02:44:49 +00:00
{
2024-01-15 19:15:18 +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 ( ) )
{
2024-01-15 19:15:18 +00:00
_fastText . LoadModel ( settings . ModelPath ) ;
2023-08-18 02:44:49 +00:00
}
}
}
2023-06-17 13:32:39 +00:00
}