You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
212 lines
7.1 KiB
212 lines
7.1 KiB
1 year ago
|
using NLog;
|
||
2 years ago
|
using Python.Runtime;
|
||
1 year ago
|
using StabilityMatrix.Core.Helper;
|
||
|
using StabilityMatrix.Core.Python.Interop;
|
||
2 years ago
|
|
||
1 year ago
|
namespace StabilityMatrix.Core.Python;
|
||
2 years ago
|
|
||
1 year ago
|
public record struct PyVersionInfo(int Major, int Minor, int Micro, string ReleaseLevel, int Serial);
|
||
2 years ago
|
|
||
1 year ago
|
public class PyRunner : IPyRunner
|
||
2 years ago
|
{
|
||
1 year ago
|
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
|
||
1 year ago
|
|
||
|
// Set by ISettingsManager.TryFindLibrary()
|
||
|
public static string HomeDir { get; set; } = string.Empty;
|
||
1 year ago
|
|
||
1 year ago
|
public static string PythonDir => Path.Combine(HomeDir, "Assets", "Python310");
|
||
1 year ago
|
public static string PythonDllPath => Path.Combine(PythonDir, "python310.dll");
|
||
|
public static string PythonExePath => Path.Combine(PythonDir, "python.exe");
|
||
|
public static string GetPipPath => Path.Combine(PythonDir, "get-pip.pyc");
|
||
|
public static string PipExePath => Path.Combine(PythonDir, "Scripts", "pip.exe");
|
||
|
public static string VenvPath => Path.Combine(PythonDir, "Scripts", "virtualenv.exe");
|
||
1 year ago
|
|
||
1 year ago
|
public static bool PipInstalled => File.Exists(PipExePath);
|
||
|
public static bool VenvInstalled => File.Exists(VenvPath);
|
||
1 year ago
|
|
||
2 years ago
|
private static readonly SemaphoreSlim PyRunning = new(1, 1);
|
||
1 year ago
|
|
||
1 year ago
|
public PyIOStream? StdOutStream;
|
||
|
public PyIOStream? StdErrStream;
|
||
2 years ago
|
|
||
2 years ago
|
/// <summary>
|
||
|
/// Initializes the Python runtime using the embedded dll.
|
||
|
/// Can be called with no effect after initialization.
|
||
|
/// </summary>
|
||
2 years ago
|
/// <exception cref="FileNotFoundException">Thrown if Python DLL not found.</exception>
|
||
1 year ago
|
public async Task Initialize()
|
||
2 years ago
|
{
|
||
|
if (PythonEngine.IsInitialized) return;
|
||
2 years ago
|
|
||
1 year ago
|
Logger.Info("Setting PYTHONHOME and PATH to {HomePath}", PythonDir);
|
||
|
Environment.SetEnvironmentVariable("PYTHONHOME", PythonDir, EnvironmentVariableTarget.Process);
|
||
1 year ago
|
// Get existing PATH
|
||
|
var currentEnvPath = Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Process);
|
||
|
// Append Python path to PATH
|
||
1 year ago
|
Environment.SetEnvironmentVariable("PATH", $"{PythonDir};{currentEnvPath}", EnvironmentVariableTarget.Process);
|
||
2 years ago
|
|
||
1 year ago
|
Logger.Info("Initializing Python runtime with DLL: {DllPath}", PythonDllPath);
|
||
2 years ago
|
// Check PythonDLL exists
|
||
1 year ago
|
if (!File.Exists(PythonDllPath))
|
||
2 years ago
|
{
|
||
1 year ago
|
Logger.Error("Python DLL not found");
|
||
1 year ago
|
throw new FileNotFoundException("Python DLL not found", PythonDllPath);
|
||
2 years ago
|
}
|
||
1 year ago
|
|
||
1 year ago
|
Runtime.PythonDLL = PythonDllPath;
|
||
2 years ago
|
PythonEngine.Initialize();
|
||
|
PythonEngine.BeginAllowThreads();
|
||
2 years ago
|
|
||
2 years ago
|
// Redirect stdout and stderr
|
||
|
StdOutStream = new PyIOStream();
|
||
|
StdErrStream = new PyIOStream();
|
||
|
await RunInThreadWithLock(() =>
|
||
|
{
|
||
|
dynamic sys = Py.Import("sys");
|
||
|
sys.stdout = StdOutStream;
|
||
|
sys.stderr = StdErrStream;
|
||
|
});
|
||
2 years ago
|
}
|
||
2 years ago
|
|
||
|
/// <summary>
|
||
|
/// One-time setup for get-pip
|
||
|
/// </summary>
|
||
1 year ago
|
public async Task SetupPip()
|
||
2 years ago
|
{
|
||
2 years ago
|
if (!File.Exists(GetPipPath))
|
||
|
{
|
||
|
throw new FileNotFoundException("get-pip not found", GetPipPath);
|
||
|
}
|
||
1 year ago
|
var p = ProcessRunner.StartProcess(PythonExePath, "-m get-pip");
|
||
2 years ago
|
await ProcessRunner.WaitForExitConditionAsync(p);
|
||
2 years ago
|
}
|
||
2 years ago
|
|
||
2 years ago
|
/// <summary>
|
||
|
/// Install a Python package with pip
|
||
|
/// </summary>
|
||
1 year ago
|
public async Task InstallPackage(string package)
|
||
2 years ago
|
{
|
||
2 years ago
|
if (!File.Exists(PipExePath))
|
||
|
{
|
||
|
throw new FileNotFoundException("pip not found", PipExePath);
|
||
|
}
|
||
2 years ago
|
var p = ProcessRunner.StartProcess(PipExePath, $"install {package}");
|
||
|
await ProcessRunner.WaitForExitConditionAsync(p);
|
||
2 years ago
|
}
|
||
2 years ago
|
|
||
2 years ago
|
/// <summary>
|
||
|
/// Run a Function with PyRunning lock as a Task with GIL.
|
||
|
/// </summary>
|
||
|
/// <param name="func">Function to run.</param>
|
||
|
/// <param name="waitTimeout">Time limit for waiting on PyRunning lock.</param>
|
||
|
/// <param name="cancelToken">Cancellation token.</param>
|
||
|
/// <exception cref="OperationCanceledException">cancelToken was canceled, or waitTimeout expired.</exception>
|
||
1 year ago
|
public async Task<T> RunInThreadWithLock<T>(Func<T> func, TimeSpan? waitTimeout = null, CancellationToken cancelToken = default)
|
||
2 years ago
|
{
|
||
2 years ago
|
// Wait to acquire PyRunning lock
|
||
|
await PyRunning.WaitAsync(cancelToken).ConfigureAwait(false);
|
||
2 years ago
|
try
|
||
2 years ago
|
{
|
||
2 years ago
|
return await Task.Run(() =>
|
||
2 years ago
|
{
|
||
2 years ago
|
using (Py.GIL())
|
||
|
{
|
||
2 years ago
|
return func();
|
||
2 years ago
|
}
|
||
2 years ago
|
}, cancelToken);
|
||
2 years ago
|
}
|
||
|
finally
|
||
|
{
|
||
|
PyRunning.Release();
|
||
|
}
|
||
2 years ago
|
}
|
||
2 years ago
|
|
||
2 years ago
|
/// <summary>
|
||
|
/// Run an Action with PyRunning lock as a Task with GIL.
|
||
|
/// </summary>
|
||
|
/// <param name="action">Action to run.</param>
|
||
|
/// <param name="waitTimeout">Time limit for waiting on PyRunning lock.</param>
|
||
|
/// <param name="cancelToken">Cancellation token.</param>
|
||
|
/// <exception cref="OperationCanceledException">cancelToken was canceled, or waitTimeout expired.</exception>
|
||
1 year ago
|
public async Task RunInThreadWithLock(Action action, TimeSpan? waitTimeout = null, CancellationToken cancelToken = default)
|
||
2 years ago
|
{
|
||
|
// Wait to acquire PyRunning lock
|
||
|
await PyRunning.WaitAsync(cancelToken).ConfigureAwait(false);
|
||
|
try
|
||
|
{
|
||
|
await Task.Run(() =>
|
||
|
{
|
||
|
using (Py.GIL())
|
||
|
{
|
||
|
action();
|
||
|
}
|
||
|
}, cancelToken);
|
||
|
}
|
||
|
finally
|
||
|
{
|
||
|
PyRunning.Release();
|
||
|
}
|
||
|
}
|
||
|
|
||
2 years ago
|
/// <summary>
|
||
|
/// Evaluate Python expression and return its value as a string
|
||
|
/// </summary>
|
||
2 years ago
|
/// <param name="expression"></param>
|
||
1 year ago
|
public async Task<string> Eval(string expression)
|
||
2 years ago
|
{
|
||
|
return await Eval<string>(expression);
|
||
|
}
|
||
2 years ago
|
|
||
2 years ago
|
/// <summary>
|
||
|
/// Evaluate Python expression and return its value
|
||
|
/// </summary>
|
||
|
/// <param name="expression"></param>
|
||
1 year ago
|
public Task<T> Eval<T>(string expression)
|
||
2 years ago
|
{
|
||
2 years ago
|
return RunInThreadWithLock(() =>
|
||
2 years ago
|
{
|
||
1 year ago
|
using var scope = Py.CreateScope();
|
||
|
var result = scope.Eval(expression);
|
||
1 year ago
|
|
||
|
// For string, cast with __str__()
|
||
|
if (typeof(T) == typeof(string))
|
||
|
{
|
||
|
return result.GetAttr("__str__").Invoke().As<T>();
|
||
|
}
|
||
2 years ago
|
return result.As<T>();
|
||
|
});
|
||
2 years ago
|
}
|
||
2 years ago
|
|
||
2 years ago
|
/// <summary>
|
||
|
/// Execute Python code without returning a value
|
||
|
/// </summary>
|
||
|
/// <param name="code"></param>
|
||
1 year ago
|
public Task Exec(string code)
|
||
2 years ago
|
{
|
||
2 years ago
|
return RunInThreadWithLock(() =>
|
||
2 years ago
|
{
|
||
1 year ago
|
using var scope = Py.CreateScope();
|
||
|
scope.Exec(code);
|
||
2 years ago
|
});
|
||
2 years ago
|
}
|
||
2 years ago
|
|
||
|
/// <summary>
|
||
|
/// Return the Python version as a PyVersionInfo struct
|
||
|
/// </summary>
|
||
1 year ago
|
public async Task<PyVersionInfo> GetVersionInfo()
|
||
2 years ago
|
{
|
||
|
var version = await RunInThreadWithLock(() =>
|
||
|
{
|
||
|
dynamic info = PythonEngine.Eval("tuple(__import__('sys').version_info)");
|
||
|
return new PyVersionInfo(
|
||
|
info[0].As<int>(),
|
||
|
info[1].As<int>(),
|
||
|
info[2].As<int>(),
|
||
|
info[3].As<string>(),
|
||
|
info[4].As<int>()
|
||
|
);
|
||
|
});
|
||
|
return version;
|
||
|
}
|
||
2 years ago
|
}
|