Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import joblib
|
| 4 |
+
import numpy as np
|
| 5 |
+
|
| 6 |
+
# 1. Load the Model and Artifacts
|
| 7 |
+
# Model and artifact paths - adjust as necessary
|
| 8 |
+
model_path = 'your_model.pkl'
|
| 9 |
+
scaler_path = 'scaler.pkl' # If you used a scaler
|
| 10 |
+
# encoder_path = 'encoder.pkl' # If you used an encoder
|
| 11 |
+
|
| 12 |
+
try:
|
| 13 |
+
model = joblib.load(model_path)
|
| 14 |
+
scaler = joblib.load(scaler_path) if scaler_path else None # Load scaler
|
| 15 |
+
# encoder = joblib.load(encoder_path) if encoder_path else None # Load encoder
|
| 16 |
+
except Exception as e:
|
| 17 |
+
print(f"Error loading model/artifacts: {e}")
|
| 18 |
+
model = None
|
| 19 |
+
|
| 20 |
+
# 2. Preprocessing Function
|
| 21 |
+
def preprocess_data(data):
|
| 22 |
+
"""
|
| 23 |
+
Preprocesses input data for the model.
|
| 24 |
+
|
| 25 |
+
Args:
|
| 26 |
+
data (dict): A dictionary containing the input data from the Gradio interface.
|
| 27 |
+
|
| 28 |
+
Returns:
|
| 29 |
+
pandas.DataFrame: A DataFrame ready for model prediction. Returns empty if error.
|
| 30 |
+
"""
|
| 31 |
+
try:
|
| 32 |
+
df = pd.DataFrame([data])
|
| 33 |
+
|
| 34 |
+
# Expected fields. Adapt to match your form inputs.
|
| 35 |
+
expected_fields = [
|
| 36 |
+
'Quality_Report__c',
|
| 37 |
+
'Delay_Days__c',
|
| 38 |
+
'Incident_Log__c',
|
| 39 |
+
'Vendor__c'
|
| 40 |
+
]
|
| 41 |
+
# 1. Check for missing fields
|
| 42 |
+
missing_fields = [field for field in expected_fields if field not in df.columns]
|
| 43 |
+
if missing_fields:
|
| 44 |
+
raise ValueError(f"Missing required fields: {', '.join(missing_fields)}")
|
| 45 |
+
# 2. Data Transformations (Adapt to your needs)
|
| 46 |
+
# Example: Scaling
|
| 47 |
+
if 'Delay_Days__c' in df.columns and scaler:
|
| 48 |
+
df['Delay_Days__c'] = df['Delay_Days__c'].fillna(0)
|
| 49 |
+
df[['Delay_Days__c']] = scaler.transform(df[['Delay_Days__c']])
|
| 50 |
+
|
| 51 |
+
# 3. One-Hot Encoding (Example)
|
| 52 |
+
# if 'Quality_Report__c' in df.columns and encoder:
|
| 53 |
+
#
|
| 54 |
+
# possible_categories = ['Good', 'Bad', 'Excellent', 'Average'] # Replace
|
| 55 |
+
# if df['Quality_Report__c'][0] not in possible_categories:
|
| 56 |
+
# df['Quality_Report__c'] = 'Average'
|
| 57 |
+
# encoded_quality = encoder.transform(df[['Quality_Report__c']])
|
| 58 |
+
# df = pd.concat([df.drop('Quality_Report__c', axis=1), pd.DataFrame(encoded_quality)], axis=1)
|
| 59 |
+
df = df[expected_fields]
|
| 60 |
+
return df
|
| 61 |
+
except ValueError as ve:
|
| 62 |
+
print(f"Error in preprocess_data: {ve}")
|
| 63 |
+
return pd.DataFrame() # Return empty DataFrame on error
|
| 64 |
+
except Exception as e:
|
| 65 |
+
print(f"Error in preprocess_data: {e}")
|
| 66 |
+
return pd.DataFrame()
|
| 67 |
+
|
| 68 |
+
# 3. Prediction Function
|
| 69 |
+
def predict_vendor_score(*args):
|
| 70 |
+
"""
|
| 71 |
+
Predicts the vendor performance score based on the input data.
|
| 72 |
+
|
| 73 |
+
Args:
|
| 74 |
+
*args: Input values from the Gradio interface.
|
| 75 |
+
|
| 76 |
+
Returns:
|
| 77 |
+
dict: A dictionary containing the prediction and potentially an error message.
|
| 78 |
+
"""
|
| 79 |
+
if model is None:
|
| 80 |
+
return {'Score': 'Model not loaded. Check server logs.', 'error': True}
|
| 81 |
+
|
| 82 |
+
# 1. Prepare input data as a dictionary. Order MUST match expected_fields in preprocess.
|
| 83 |
+
input_data = {
|
| 84 |
+
'Quality_Report__c': args[0],
|
| 85 |
+
'Delay_Days__c': args[1],
|
| 86 |
+
'Incident_Log__c': args[2],
|
| 87 |
+
'Vendor__c': args[3],
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
# 2. Preprocess the data
|
| 91 |
+
processed_df = preprocess_data(input_data)
|
| 92 |
+
|
| 93 |
+
if processed_df.empty:
|
| 94 |
+
return {'Score': 'Error in input data. Check logs.', 'error': True}
|
| 95 |
+
|
| 96 |
+
# 3. Make Prediction
|
| 97 |
+
try:
|
| 98 |
+
prediction = model.predict(processed_df)[0] # Get the first element
|
| 99 |
+
# prediction = prediction.tolist() # convert numpy to list
|
| 100 |
+
return {'Score': prediction, 'error': False}
|
| 101 |
+
except Exception as e:
|
| 102 |
+
print(f"Error during prediction: {e}")
|
| 103 |
+
return {'Score': f'Error during prediction: {e}', 'error': True}
|
| 104 |
+
|
| 105 |
+
# 4. Gradio Interface
|
| 106 |
+
iface = gr.Interface(
|
| 107 |
+
fn=predict_vendor_score,
|
| 108 |
+
inputs=[
|
| 109 |
+
gr.Dropdown(['Good', 'Bad', 'Excellent', 'Average'], label="Quality Report"), # Example
|
| 110 |
+
gr.Number(label="Delay Days"),
|
| 111 |
+
gr.Number(label="Incident Log"),
|
| 112 |
+
gr.Textbox(label="Vendor ID"), # Or a dropdown if you have vendor names
|
| 113 |
+
],
|
| 114 |
+
outputs=gr.outputs.HighlightedText(
|
| 115 |
+
label="Prediction",
|
| 116 |
+
# displayed_value_interpretation=lambda x: {"Score": x} # Simplest approach
|
| 117 |
+
),
|
| 118 |
+
# examples=[ # Example data (optional)
|
| 119 |
+
# ["Good", 5, 2, "V123"],
|
| 120 |
+
# ["Excellent", 0, 0, "V456"],
|
| 121 |
+
# ["Bad", 10, 5, "V789"],
|
| 122 |
+
# ],
|
| 123 |
+
title="Subcontractor Performance Score Predictor",
|
| 124 |
+
description="Enter subcontractor data to get a performance score.",
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
# 5. Launch the Interface
|
| 128 |
+
if __name__ == "__main__":
|
| 129 |
+
iface.launch()
|