Spaces:
Sleeping
Sleeping
File size: 2,805 Bytes
b565f0a 55f664e 00b26e4 b565f0a 00b26e4 b565f0a e588032 b565f0a e588032 b565f0a 6669778 b565f0a 6dfb9dc b565f0a 28d8ff1 b565f0a |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 |
"""
Webapp Front End
"""
import gradio as gr
import joblib
from data.clean_data import fetch_check
from data.value_maps import category_maps, binary_maps
MODEL_PATH = "Random_Foresttest_model.pkl"
DEFAULT_VALUE = 99
try:
rf_model = joblib.load(MODEL_PATH)
joblib.dump(rf_model, MODEL_PATH)
except FileNotFoundError as e:
raise FileNotFoundError(
f"Model file not found at {MODEL_PATH}. Please check the path."
) from e
og_df = fetch_check(to_fetch=True, to_fillna=True, to_dropna=True)
binary_inputs = {
feature: gr.Radio(
choices=list(mapping.keys()),
label=feature.replace("_", " "),
)
for feature, mapping in binary_maps.items()
if mapping
}
categorical_inputs = {
feature: gr.Dropdown(
choices=list(mapping.keys()),
label=feature.replace("_", " "),
)
for feature, mapping in category_maps.items()
if mapping
}
input_types = list(categorical_inputs.values()) + list(binary_inputs.values())
for i in categorical_inputs:
print(f"input_types: {i}")
for i in binary_inputs:
print(f"input_types: {i}")
for i in input_types:
print(f"input_types: {i}")
def predict_outcome(*user_inputs):
"""
Converts user inputs into model-friendly format, runs the prediction,
and returns the result.
"""
# Use maps to set expected features
expected_features = list(categorical_inputs.keys()) + list(binary_inputs.keys())
input_data = dict(zip(expected_features, user_inputs))
# Ensure all required features are present and that the numerical values are used for the model
input_data = {}
for feature, user_input in zip(expected_features, user_inputs):
if feature in binary_maps:
# Convert 'Yes'/'No' to 1/0
input_data[feature] = binary_maps[feature].get(user_input, DEFAULT_VALUE)
elif feature in category_maps:
# Convert categorical values
input_data[feature] = category_maps[feature].get(user_input, DEFAULT_VALUE)
else:
# Default value for unexpected inputs
input_data[feature] = DEFAULT_VALUE
# Create a DataFrame for prediction
input_df = pd.DataFrame([input_data])[expected_features]
# Perform prediction
try:
prediction = rf_model.predict(input_df)[0]
return "High Risk" if prediction == 1 else "Low Risk"
except ValueError as e:
raise ValueError(f"Error during prediction: {e}") from e
def build_interface():
"""
Constructs the Gradio interface dynamically based on the dataset.
"""
outputs = gr.Label(label="Prediction")
return gr.Interface(fn=predict_outcome, inputs=input_types, outputs=outputs)
# Run the app
if __name__ == "__main__":
interface = build_interface()
interface.launch()
|