使用源码生成系统将项目中附加的 .py 文件编译为相应的 .net 类供调用
CSnakes
https://github.com/tonybaloney/CSnakes
https://tonybaloney.github.io/CSnakes/
https://www.bilibili.com/video/BV1hPjfzkEtF
var builder = Host.CreateDefaultBuilder(args)
.ConfigureServices(services =>
{
var home = Path.Join(Environment.CurrentDirectory, "."); /* Path to your Python modules */
services
.WithPython()
.WithHome(home)
.FromRedistributable(); // Download Python 3.12 and store it locally
/* Add these methods to configure a virtual environment and install packages from requirements.txt */
// 配置虚拟环境
.WithVirtualEnvironment(Path.Join(home, ".venv"))
// 安装 requirements.txt 中指定的包
.WithPipInstaller(); // Optional - installs packages listed in requirements.txt on startup
});
var app = builder.Build();
var env = app.Services.GetRequiredService<IPythonEnvironment>();
// Demo 为 python 文件名
var module = env.Demo();
// 调用 Python 函数
var result = module.HelloWorld("Alice");
Console.WriteLine(result); // Hello, Alice!
TransformersSharp
基于 CSnakes 创建的 Hugging Face Transformers
的 .net 包装器
https://tonybaloney.github.io/TransformersSharp/