Files
AI-Stock-Trader/WebServer/Controllers/PythonInterop.cs
T
2026-02-17 18:39:02 -08:00

41 lines
1.5 KiB
C#

using Python.Runtime;
namespace PythonInterop {
public class AIModule {
public AIModule(string PythonPathBase = "/usr/local/", string PythonVersion = "python3.11") {
// Use the user provided python runner
Runtime.PythonDLL = PythonPathBase + $"lib/lib{PythonVersion}.so";
// Use our local environment for the python libraries
PythonEngine.PythonHome = PythonPathBase;
// Include all the paths for python packages most importantly our venv
PythonEngine.PythonPath = $"{PythonPathBase}lib/{PythonVersion}:{PythonPathBase}lib/{PythonVersion}/lib-dynload:{PythonPathBase}lib/{PythonVersion}/site-packages:{Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "AIPython")}";
// Initiilize python
PythonEngine.Initialize();
// Needed because C# calls the python from each connections worker thread
PythonEngine.BeginAllowThreads();
}
// This is thread blocking, runs on the main thread, and takes multiple minutes so probabaly need to run on a background thread at some point
public void TrainAI() {
using (Py.GIL()) {
dynamic datapuller = Py.Import("ai-trainer");
dynamic result = datapuller.TrainAI();
}
}
public void PredictAI() {
using (Py.GIL()) {
dynamic main = Py.Import("ai-predictor");
dynamic result = main.Predict();
}
}
}
}