using System.Diagnostics; using System.Runtime.InteropServices; using Newtonsoft.Json; namespace Application.Endpoints.SicknessPrediction; public class PythonScriptRunner { public static async Task RunPythonScript(string scriptPath, string args) { var solutionRoot = PathHelper.GetSolutionRoot(); var pythonExecutablePath = Path.Combine(solutionRoot, "venv", "Scripts", "python.exe"); using var process = new Process(); process.StartInfo = new ProcessStartInfo(pythonExecutablePath, $"\"{scriptPath}\" \"{args}\"") { RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = true }; try { process.Start(); var output = await process.StandardOutput.ReadToEndAsync(); var error = await process.StandardError.ReadToEndAsync(); await process.WaitForExitAsync(); if (process.ExitCode == 0) // Assuming exit code 0 as a success. try { Console.WriteLine(output); var response = JsonConvert.DeserializeObject(output); return new BaseResponse { StatusCode = response.StatusCode, Message = response.Message, Data = response.Data }; } catch (JsonException ex) { Console.WriteLine($"JSON Error: {ex.Message}"); return new BaseResponse { StatusCode = 500, Message = "Error parsing JSON response." }; } Console.WriteLine(error); return new BaseResponse { StatusCode = 500, Message = error }; } catch (Exception ex) { Console.WriteLine($"Execution Error: {ex.Message}"); return new BaseResponse { StatusCode = 500, Message = $"An error occurred while executing the Python script: {ex.Message}" }; } } } public static class PathHelper { public static string GetSolutionRoot() { var currentDir = Directory.GetCurrentDirectory(); var solutionRoot = Directory.GetParent(currentDir)?.FullName; if (solutionRoot == null) throw new InvalidOperationException("Failed to find the solution root directory."); return solutionRoot; } public static string GetPythonExecutablePath() { var solutionRoot = GetSolutionRoot(); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) return Path.Combine(solutionRoot, "venv", "Scripts", "python.exe"); if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) return Path.Combine(solutionRoot, "venv", "bin", "python"); throw new InvalidOperationException("Unsupported operating system."); } } public class BaseResponsePython { public int StatusCode { get; set; } public string Message { get; set; } = string.Empty; public List Data { get; set; } = []; // Correct initialization and make it a property } public class PredictionData // Removed abstract if no inheritance is required { public string Disease { get; set; } = string.Empty; public double Probability { get; set; } }