Update app.py
Browse files
app.py
CHANGED
@@ -3,29 +3,70 @@ import pandas as pd
|
|
3 |
import numpy as np
|
4 |
import joblib
|
5 |
import onnxruntime as ort
|
|
|
|
|
6 |
|
7 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
8 |
try:
|
9 |
-
|
10 |
-
|
11 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
12 |
|
13 |
model_loaded = True
|
14 |
scaler_loaded = True
|
15 |
-
|
16 |
-
|
|
|
|
|
|
|
|
|
|
|
17 |
model_loaded = False
|
18 |
-
scaler_loaded = False
|
|
|
|
|
|
|
19 |
ort_session = None
|
20 |
scaler = None
|
21 |
-
|
|
|
|
|
|
|
22 |
|
23 |
def predict_risk(age, sex, cd4_count, viral_load, wbc_count, hemoglobin, platelet_count):
|
24 |
-
"""
|
25 |
-
|
26 |
-
"""
|
27 |
if not model_loaded or not scaler_loaded:
|
28 |
-
|
29 |
|
30 |
try:
|
31 |
# 1. Create a DataFrame
|
@@ -41,8 +82,8 @@ def predict_risk(age, sex, cd4_count, viral_load, wbc_count, hemoglobin, platele
|
|
41 |
input_df = pd.DataFrame(input_data)
|
42 |
|
43 |
# 2. Standardize the data
|
44 |
-
scaled_values = scaler.transform(input_df[feature_names])
|
45 |
-
scaled_df = pd.DataFrame(scaled_values, columns=feature_names)
|
46 |
|
47 |
# 3. ONNX Prediction
|
48 |
input_array = scaled_df[feature_names].values.astype(np.float32) # Enforce float32
|
@@ -56,8 +97,8 @@ def predict_risk(age, sex, cd4_count, viral_load, wbc_count, hemoglobin, platele
|
|
56 |
return f"High Risk Probability: {risk_probability:.4f}"
|
57 |
|
58 |
except Exception as e:
|
59 |
-
|
60 |
-
|
61 |
|
62 |
# Define Gradio inputs
|
63 |
age_input = gr.Number(label="Age", value=30)
|
|
|
3 |
import numpy as np
|
4 |
import joblib
|
5 |
import onnxruntime as ort
|
6 |
+
import os
|
7 |
+
import logging
|
8 |
|
9 |
+
# Configure logging
|
10 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
11 |
+
|
12 |
+
# Set feature names. CRUCIAL - must match your training data
|
13 |
+
feature_names = ['Age', 'Sex', 'CD4+ T-cell count', 'Viral load', 'WBC count', 'Hemoglobin', 'Platelet count']
|
14 |
+
|
15 |
+
# Initialize model and scaler (set to None initially)
|
16 |
+
ort_session = None
|
17 |
+
scaler = None
|
18 |
+
model_loaded = False
|
19 |
+
scaler_loaded = False
|
20 |
+
|
21 |
+
# --- Attempt to Load Model and Scaler ---
|
22 |
try:
|
23 |
+
# 1. Set the current working directory (as a precaution)
|
24 |
+
script_dir = os.path.dirname(os.path.abspath(__file__))
|
25 |
+
os.chdir(script_dir)
|
26 |
+
logging.info(f"Current working directory set to: {os.getcwd()}")
|
27 |
+
|
28 |
+
# 2. Check if files exist
|
29 |
+
model_path = "hiv_model.onnx"
|
30 |
+
scaler_path = "hiv_scaler.pkl"
|
31 |
+
|
32 |
+
if not os.path.exists(model_path):
|
33 |
+
logging.error(f"Model file not found: {model_path}")
|
34 |
+
raise FileNotFoundError(f"Model file not found: {model_path}")
|
35 |
+
|
36 |
+
if not os.path.exists(scaler_path):
|
37 |
+
logging.error(f"Scaler file not found: {scaler_path}")
|
38 |
+
raise FileNotFoundError(f"Scaler file not found: {scaler_path}")
|
39 |
+
|
40 |
+
# 3. Load the model and scaler
|
41 |
+
ort_session = ort.InferenceSession(model_path)
|
42 |
+
scaler = joblib.load(scaler_path)
|
43 |
|
44 |
model_loaded = True
|
45 |
scaler_loaded = True
|
46 |
+
|
47 |
+
logging.info("Model and scaler loaded successfully.")
|
48 |
+
|
49 |
+
except FileNotFoundError as e:
|
50 |
+
logging.error(f"File not found: {e}")
|
51 |
+
ort_session = None
|
52 |
+
scaler = None
|
53 |
model_loaded = False
|
54 |
+
scaler_loaded = False # Make sure these are false if loading fails!
|
55 |
+
|
56 |
+
except Exception as e:
|
57 |
+
logging.exception(f"An error occurred while loading the model or scaler: {e}")
|
58 |
ort_session = None
|
59 |
scaler = None
|
60 |
+
model_loaded = False
|
61 |
+
scaler_loaded = False
|
62 |
+
# Log the full exception traceback for debugging
|
63 |
+
# --- End Model Loading ---
|
64 |
|
65 |
def predict_risk(age, sex, cd4_count, viral_load, wbc_count, hemoglobin, platelet_count):
|
66 |
+
"""Predicts HIV risk probability based on input features."""
|
67 |
+
|
|
|
68 |
if not model_loaded or not scaler_loaded:
|
69 |
+
return "Model or scaler not loaded. Check the logs for errors. Ensure 'hiv_model.onnx' and 'hiv_scaler.pkl' are in the same directory."
|
70 |
|
71 |
try:
|
72 |
# 1. Create a DataFrame
|
|
|
82 |
input_df = pd.DataFrame(input_data)
|
83 |
|
84 |
# 2. Standardize the data
|
85 |
+
scaled_values = scaler.transform(input_df[feature_names]) #Use ALL features now.
|
86 |
+
scaled_df = pd.DataFrame(scaled_values, columns=feature_names) #Use ALL feature names now.
|
87 |
|
88 |
# 3. ONNX Prediction
|
89 |
input_array = scaled_df[feature_names].values.astype(np.float32) # Enforce float32
|
|
|
97 |
return f"High Risk Probability: {risk_probability:.4f}"
|
98 |
|
99 |
except Exception as e:
|
100 |
+
logging.exception(f"An error occurred during prediction: {e}")
|
101 |
+
return f"An error occurred during prediction: {e}. Check the logs for details."
|
102 |
|
103 |
# Define Gradio inputs
|
104 |
age_input = gr.Number(label="Age", value=30)
|