finalizare 1.0
This commit is contained in:
@@ -1,55 +1,97 @@
|
||||
using System.Diagnostics;
|
||||
using System.Runtime.InteropServices;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace Application.Endpoints.SicknessPrediction;
|
||||
|
||||
public class PythonScriptRunner
|
||||
{
|
||||
public async Task<BaseResponse> RunPythonScript(string scriptPath, string args)
|
||||
public static async Task<BaseResponse> RunPythonScript(string scriptPath, string args)
|
||||
{
|
||||
var response = new BaseResponse();
|
||||
using (Process process = new Process())
|
||||
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}\"")
|
||||
{
|
||||
process.StartInfo = new ProcessStartInfo("python", $"\"{scriptPath}\" \"{args}\"")
|
||||
{
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true, // Redirect standard error to capture any errors.
|
||||
UseShellExecute = false,
|
||||
CreateNoWindow = true,
|
||||
};
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true,
|
||||
UseShellExecute = false,
|
||||
CreateNoWindow = true
|
||||
};
|
||||
|
||||
try
|
||||
{
|
||||
process.Start();
|
||||
|
||||
// Read output and error streams.
|
||||
var output = await process.StandardOutput.ReadToEndAsync();
|
||||
var error = await process.StandardError.ReadToEndAsync();
|
||||
|
||||
process.WaitForExit();
|
||||
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.
|
||||
if (process.ExitCode == 0) // Assuming exit code 0 as a success.
|
||||
try
|
||||
{
|
||||
Console.WriteLine(output);
|
||||
response.StatusCode = HttpStatusCodes.OK;
|
||||
response.Message = "Success";
|
||||
response.Data = output;
|
||||
var response = JsonConvert.DeserializeObject<BaseResponsePython>(output);
|
||||
return new BaseResponse()
|
||||
{
|
||||
StatusCode = response.StatusCode,
|
||||
Message = response.Message,
|
||||
Data = response.Data
|
||||
};
|
||||
}
|
||||
else
|
||||
catch (JsonException ex)
|
||||
{
|
||||
Console.WriteLine(error);
|
||||
response.StatusCode = HttpStatusCodes.InternalServerError;
|
||||
response.Message = error; // Using the error output as the message if not successful.
|
||||
response.Data = null;
|
||||
Console.WriteLine($"JSON Error: {ex.Message}");
|
||||
return new BaseResponse { StatusCode = 500, Message = "Error parsing JSON response." };
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
response.StatusCode = HttpStatusCodes.InternalServerError;
|
||||
response.Message = $"An error occurred while executing the Python script: {ex.Message}";
|
||||
response.Data = null;
|
||||
}
|
||||
|
||||
return 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<PredictionData> 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; }
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
namespace Application.Endpoints.SicknessPrediction;
|
||||
|
||||
public class SicknessPredictionCommand
|
||||
{
|
||||
public string Text { get; set; } = string.Empty;
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
namespace Application.Endpoints.SicknessPrediction;
|
||||
|
||||
public class SicknessPredictionDto
|
||||
{
|
||||
public string Text { get; set; }
|
||||
}
|
||||
@@ -2,10 +2,10 @@
|
||||
|
||||
public class SicknessPredictionHandler
|
||||
{
|
||||
public async Task<BaseResponse> GetPrediction(SicknessPredictionDto dto)
|
||||
public static async Task<BaseResponse> GetPrediction(SicknessPredictionCommand command)
|
||||
{
|
||||
var validation = new SicknessPredictionValidator();
|
||||
var validationResult = await validation.ValidateAsync(dto);
|
||||
var validationResult = await validation.ValidateAsync(command);
|
||||
|
||||
if (!validationResult.IsValid)
|
||||
{
|
||||
@@ -20,13 +20,14 @@ public class SicknessPredictionHandler
|
||||
Data = null
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
var currentDirectory = Directory.GetCurrentDirectory(); // gets the current working directory
|
||||
var applicationDirectory = Path.Combine(Directory.GetParent(currentDirectory)?.FullName, "Application");
|
||||
|
||||
var scriptPath = Path.Combine(applicationDirectory, "Endpoints","SicknessPrediction", "SicknessPredictionScript.py");
|
||||
var scriptPath = Path.Combine(applicationDirectory, "Endpoints", "SicknessPrediction",
|
||||
"SicknessPredictionScript.py");
|
||||
var scriptRunner = new PythonScriptRunner();
|
||||
var result = await scriptRunner.RunPythonScript(scriptPath, dto.Text);
|
||||
var result = await PythonScriptRunner.RunPythonScript(scriptPath, command.Text);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -46,7 +46,6 @@ class DiseasePredictor:
|
||||
self.model.fit(self.X_train, self.y_train) # X_train is a DataFrame with feature names
|
||||
logging.info(f"Training accuracy: {self.model.score(self.X_test, self.y_test):.2f}")
|
||||
|
||||
|
||||
def extract_features(self, text):
|
||||
logging.info("Extracting features from text")
|
||||
|
||||
@@ -118,7 +117,7 @@ class DiseasePredictor:
|
||||
if count == 3:
|
||||
break
|
||||
# Return the JSON object
|
||||
return json.dumps(json_output, indent=4)
|
||||
return json.dumps(json_output)
|
||||
|
||||
|
||||
# Example usage:
|
||||
@@ -127,11 +126,11 @@ if __name__ == "__main__":
|
||||
if len(sys.argv) != 2:
|
||||
logging.error("Incorrect number of arguments provided.")
|
||||
json_output = {
|
||||
"StatusCode": 400,
|
||||
"Message": "Incorrect number of arguments provided.",
|
||||
"Data": []
|
||||
}
|
||||
print(json.dumps(json_output, indent=4))
|
||||
"StatusCode": 400,
|
||||
"Message": "Incorrect number of arguments provided.",
|
||||
"Data": []
|
||||
}
|
||||
print(json.dumps(json_output))
|
||||
sys.exit(1)
|
||||
|
||||
logging.basicConfig(filename='disease_prediction.log', level=logging.INFO,
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
namespace Application.Endpoints.SicknessPrediction;
|
||||
|
||||
public class SicknessPredictionValidator : AbstractValidator<SicknessPredictionDto>
|
||||
public class SicknessPredictionValidator : AbstractValidator<SicknessPredictionCommand>
|
||||
{
|
||||
public SicknessPredictionValidator()
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user