Update modules/supply_failure.py
Browse files- modules/supply_failure.py +106 -263
modules/supply_failure.py
CHANGED
@@ -1,12 +1,6 @@
|
|
1 |
-
from flask import Blueprint, render_template, request, jsonify, redirect, url_for, flash
|
2 |
import pandas as pd
|
3 |
import numpy as np
|
4 |
-
import plotly.express as px
|
5 |
-
import plotly.utils
|
6 |
-
import json
|
7 |
-
import os
|
8 |
-
import joblib
|
9 |
-
from datetime import datetime
|
10 |
from sklearn.model_selection import train_test_split
|
11 |
from sklearn.preprocessing import StandardScaler, LabelEncoder
|
12 |
from sklearn.ensemble import RandomForestClassifier
|
@@ -15,20 +9,18 @@ import random
|
|
15 |
|
16 |
supply_failure_bp = Blueprint('supply_failure', __name__, url_prefix='/predict/supply_failure')
|
17 |
|
18 |
-
|
19 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
20 |
|
21 |
-
def get_current_df_supply():
|
22 |
-
try:
|
23 |
-
csv_path = session.get('supply_csv_path')
|
24 |
-
if csv_path and os.path.exists(csv_path):
|
25 |
-
return pd.read_csv(csv_path)
|
26 |
-
return None
|
27 |
-
except Exception as e:
|
28 |
-
print(f"Error in get_current_df_supply: {str(e)}")
|
29 |
-
return None
|
30 |
|
31 |
def get_summary_stats_supply(df):
|
|
|
32 |
return {
|
33 |
'total_rows': len(df),
|
34 |
'total_columns': len(df.columns),
|
@@ -39,76 +31,50 @@ def get_summary_stats_supply(df):
|
|
39 |
}
|
40 |
|
41 |
def preprocess_data_supply(df, for_prediction=False, label_encoders=None):
|
|
|
42 |
df_processed = df.copy()
|
43 |
-
|
44 |
-
# Identify date columns based on known names
|
45 |
-
date_cols = ['order_date', 'promised_delivery_date', 'actual_delivery_date']
|
46 |
|
47 |
-
|
|
|
|
|
48 |
for col in date_cols:
|
49 |
if col in df_processed.columns:
|
50 |
-
# Convert to datetime, coercing errors to NaT
|
51 |
df_processed[col] = pd.to_datetime(df_processed[col], errors='coerce')
|
52 |
-
|
53 |
-
|
54 |
-
if not df_processed[col].isnull().all():
|
55 |
-
df_processed[f'{col}_day_of_week'] = df_processed[col].dt.dayofweek.fillna(-1) # -1 for NaN dates
|
56 |
-
df_processed[f'{col}_month'] = df_processed[col].dt.month.fillna(-1)
|
57 |
-
df_processed[f'{col}_year'] = df_processed[col].dt.year.fillna(-1)
|
58 |
-
df_processed[f'{col}_day'] = df_processed[col].dt.day.fillna(-1)
|
59 |
-
else: # If all dates are NaT, add dummy columns filled with -1
|
60 |
-
df_processed[f'{col}_day_of_week'] = -1
|
61 |
-
df_processed[f'{col}_month'] = -1
|
62 |
-
df_processed[f'{col}_year'] = -1
|
63 |
-
df_processed[f'{col}_day'] = -1
|
64 |
df_processed = df_processed.drop(columns=[col])
|
65 |
|
66 |
-
# Identify numerical and categorical columns after date processing
|
67 |
-
categorical_columns = []
|
68 |
-
numerical_columns = []
|
69 |
-
|
70 |
-
for column in df_processed.columns:
|
71 |
-
if pd.api.types.is_numeric_dtype(df_processed[column]):
|
72 |
-
numerical_columns.append(column)
|
73 |
-
else:
|
74 |
-
try:
|
75 |
-
# Attempt to convert to numeric, if successful, it's numeric
|
76 |
-
if pd.to_numeric(df_processed[column].dropna()).notna().all():
|
77 |
-
numerical_columns.append(column)
|
78 |
-
else:
|
79 |
-
categorical_columns.append(column)
|
80 |
-
except ValueError:
|
81 |
-
categorical_columns.append(column)
|
82 |
-
|
83 |
-
# Encode categorical variables
|
84 |
current_label_encoders = {}
|
85 |
-
if not for_prediction:
|
86 |
for col in categorical_columns:
|
87 |
if col in df_processed.columns:
|
88 |
le = LabelEncoder()
|
89 |
-
df_processed[col] = le.fit_transform(df_processed[col].astype(str).fillna('
|
90 |
current_label_encoders[col] = le
|
91 |
-
else:
|
92 |
for col, le in label_encoders.items():
|
93 |
if col in df_processed.columns:
|
94 |
-
df_processed[col] = df_processed[col].astype(str).apply(
|
95 |
-
lambda x: le.transform([x])[0] if x in le.classes_ else -1
|
96 |
-
)
|
97 |
|
98 |
-
#
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
|
103 |
return df_processed, current_label_encoders
|
104 |
|
105 |
|
106 |
@supply_failure_bp.route('/', methods=['GET'])
|
107 |
def show_supply_failure():
|
|
|
108 |
return render_template('supply_failure.html', title="Supply Failure Prediction")
|
109 |
|
|
|
110 |
@supply_failure_bp.route('/upload_file_supply', methods=['POST'])
|
111 |
def upload_file_supply():
|
|
|
|
|
112 |
if 'supply_file' not in request.files:
|
113 |
flash('No file selected')
|
114 |
return redirect(url_for('supply_failure.show_supply_failure'))
|
@@ -119,71 +85,53 @@ def upload_file_supply():
|
|
119 |
return redirect(url_for('supply_failure.show_supply_failure'))
|
120 |
|
121 |
try:
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
file.save(file_path)
|
127 |
-
session['supply_csv_path'] = file_path
|
128 |
-
|
129 |
-
df = pd.read_csv(file_path)
|
130 |
-
preview_data = df.head().to_dict('records')
|
131 |
-
summary_stats = get_summary_stats_supply(df)
|
132 |
-
session['original_columns_supply'] = df.columns.tolist()
|
133 |
|
134 |
return render_template('supply_failure.html',
|
135 |
title="Supply Failure Prediction",
|
136 |
preview_data=preview_data,
|
137 |
-
columns=
|
138 |
summary_stats=summary_stats)
|
139 |
-
|
140 |
except Exception as e:
|
141 |
flash(f'Error processing file: {str(e)}')
|
142 |
return redirect(url_for('supply_failure.show_supply_failure'))
|
143 |
|
|
|
144 |
@supply_failure_bp.route('/run_prediction', methods=['POST'])
|
145 |
def run_prediction_supply():
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
target_col = 'failure_flag' # Fixed target column as per definition
|
152 |
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
joblib.dump(label_encoders, encoders_path)
|
157 |
-
session['supply_encoders_path'] = encoders_path
|
158 |
|
159 |
-
if
|
160 |
-
return jsonify({'success': False, 'error': f"Target column '{
|
161 |
|
162 |
-
X = df_processed.drop(columns=[
|
163 |
-
y = df_processed[
|
|
|
164 |
|
165 |
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
feature_importance = sorted(
|
177 |
-
zip(feature_names, importances),
|
178 |
-
key=lambda x: x[1],
|
179 |
-
reverse=True
|
180 |
-
)[:5]
|
181 |
-
|
182 |
top_features = [{'feature': f, 'importance': float(imp)} for f, imp in feature_importance]
|
183 |
|
184 |
-
session['supply_feature_names'] = X.columns.tolist()
|
185 |
-
session['supply_target_column_name'] = target_col
|
186 |
-
|
187 |
metrics = {
|
188 |
'Accuracy': accuracy_score(y_test, y_pred),
|
189 |
'Precision': precision_score(y_test, y_pred, average='weighted', zero_division=0),
|
@@ -191,173 +139,68 @@ def run_prediction_supply():
|
|
191 |
'F1 Score': f1_score(y_test, y_pred, average='weighted', zero_division=0)
|
192 |
}
|
193 |
|
194 |
-
|
195 |
-
scaler_path = os.path.join(UPLOAD_FOLDER, f'supply_scaler_{datetime.now().strftime("%Y%m%d_%H%M%S")}.joblib')
|
196 |
-
|
197 |
-
joblib.dump(clf, model_path)
|
198 |
-
joblib.dump(scaler, scaler_path)
|
199 |
-
|
200 |
-
session['supply_model_path'] = model_path
|
201 |
-
session['supply_scaler_path'] = scaler_path
|
202 |
-
|
203 |
-
return jsonify({
|
204 |
-
'success': True,
|
205 |
-
'metrics': metrics,
|
206 |
-
'top_features': top_features,
|
207 |
-
})
|
208 |
-
|
209 |
except Exception as e:
|
210 |
-
|
211 |
-
return jsonify({'success': False, 'error': str(e)})
|
212 |
|
213 |
@supply_failure_bp.route('/get_form_data', methods=['GET'])
|
214 |
def get_form_data_supply():
|
215 |
-
|
216 |
-
|
217 |
-
|
218 |
-
|
219 |
-
|
220 |
-
|
221 |
-
|
222 |
-
|
223 |
-
|
224 |
-
|
225 |
-
|
226 |
-
|
227 |
-
|
228 |
-
|
229 |
-
|
230 |
-
|
231 |
-
|
232 |
-
|
233 |
-
|
234 |
-
|
235 |
-
|
236 |
-
|
237 |
-
|
238 |
-
|
239 |
-
|
240 |
-
|
241 |
-
|
242 |
-
|
243 |
-
|
244 |
-
|
245 |
-
|
246 |
-
|
247 |
-
else:
|
248 |
-
default_value = parsed_date.strftime('%Y-%m-%d %H:%M:%S')
|
249 |
-
except Exception:
|
250 |
-
default_value = "YYYY-MM-DD HH:MM:SS"
|
251 |
-
else: # Categorical or other types
|
252 |
-
unique_vals_str = [str(x) for x in df[col].dropna().unique()]
|
253 |
-
if unique_vals_str:
|
254 |
-
default_value = random.choice(unique_vals_str)
|
255 |
-
else:
|
256 |
-
default_value = ""
|
257 |
-
|
258 |
-
if pd.api.types.is_numeric_dtype(df[col]):
|
259 |
-
form_fields.append({
|
260 |
-
'name': col,
|
261 |
-
'type': 'number',
|
262 |
-
'default_value': default_value
|
263 |
-
})
|
264 |
-
elif col in ['order_date', 'promised_delivery_date', 'actual_delivery_date']:
|
265 |
-
form_fields.append({
|
266 |
-
'name': col,
|
267 |
-
'type': 'text',
|
268 |
-
'placeholder': 'YYYY-MM-DD HH:MM:SS',
|
269 |
-
'default_value': default_value
|
270 |
-
})
|
271 |
-
else: # Categorical
|
272 |
-
unique_values = [str(x) for x in df[col].dropna().unique().tolist()]
|
273 |
-
form_fields.append({
|
274 |
-
'name': col,
|
275 |
-
'type': 'select',
|
276 |
-
'options': unique_values,
|
277 |
-
'default_value': default_value
|
278 |
-
})
|
279 |
-
|
280 |
-
return jsonify({'success': True, 'form_fields': form_fields})
|
281 |
-
|
282 |
-
except Exception as e:
|
283 |
-
print(f"Error in get_form_data_supply: {e}")
|
284 |
-
return jsonify({'success': False, 'error': str(e)})
|
285 |
|
286 |
|
287 |
@supply_failure_bp.route('/predict_single', methods=['POST'])
|
288 |
def predict_single_supply():
|
|
|
|
|
|
|
|
|
289 |
try:
|
290 |
-
model_path = session.get('supply_model_path')
|
291 |
-
scaler_path = session.get('supply_scaler_path')
|
292 |
-
encoders_path = session.get('supply_encoders_path')
|
293 |
-
feature_names = session.get('supply_feature_names')
|
294 |
-
target_col = session.get('supply_target_column_name')
|
295 |
-
original_uploaded_columns = session.get('original_columns_supply')
|
296 |
-
|
297 |
-
if not all([model_path, scaler_path, encoders_path, feature_names, target_col, original_uploaded_columns]):
|
298 |
-
return jsonify({'success': False, 'error': 'Model or preprocessing artifacts not found for supply chain. Please train a model first.'})
|
299 |
-
|
300 |
-
model = joblib.load(model_path)
|
301 |
-
scaler = joblib.load(scaler_path)
|
302 |
-
label_encoders = joblib.load(encoders_path)
|
303 |
-
|
304 |
input_data = request.json
|
305 |
-
|
306 |
-
return jsonify({'success': False, 'error': 'No input data provided.'})
|
307 |
-
|
308 |
-
full_input_df = pd.DataFrame(columns=original_uploaded_columns)
|
309 |
-
single_row_input_df = pd.DataFrame([input_data])
|
310 |
-
|
311 |
-
for col in original_uploaded_columns:
|
312 |
-
if col in single_row_input_df.columns:
|
313 |
-
full_input_df.loc[0, col] = single_row_input_df.loc[0, col]
|
314 |
-
else:
|
315 |
-
full_input_df.loc[0, col] = np.nan
|
316 |
-
|
317 |
-
preprocessed_input_df, _ = preprocess_data_supply(full_input_df.copy(), for_prediction=True, label_encoders=label_encoders)
|
318 |
|
319 |
-
|
320 |
|
321 |
-
|
322 |
-
|
323 |
-
final_input_features[col] = pd.to_numeric(preprocessed_input_df[col], errors='coerce').values
|
324 |
-
else:
|
325 |
-
final_input_features[col] = 0.0
|
326 |
-
|
327 |
-
final_input_features = final_input_features.fillna(0.0)
|
328 |
|
329 |
-
input_scaled =
|
330 |
|
331 |
-
|
|
|
332 |
|
333 |
-
|
334 |
-
prediction_display = prediction_value
|
335 |
-
if target_col in label_encoders and prediction_value in label_encoders[target_col].classes_: # Check if target was encoded and value is in classes
|
336 |
-
prediction_display = str(label_encoders[target_col].inverse_transform([prediction_value])[0])
|
337 |
-
else:
|
338 |
-
if isinstance(prediction_value, np.number):
|
339 |
-
prediction_display = float(prediction_value)
|
340 |
-
else:
|
341 |
-
prediction_display = prediction_value # Keep as is if not np.number
|
342 |
-
|
343 |
-
# Convert 0/1 to "No Failure"/"Failure" based on the definition for failure_flag
|
344 |
-
if prediction_display == 0 or prediction_display == "0":
|
345 |
-
user_friendly_prediction = "Delivery Successful"
|
346 |
-
elif prediction_display == 1 or prediction_display == "1":
|
347 |
-
user_friendly_prediction = "Delivery Failed"
|
348 |
-
else:
|
349 |
-
user_friendly_prediction = str(prediction_display) # Fallback if target is something else
|
350 |
|
351 |
-
probability
|
352 |
-
if hasattr(model, 'predict_proba'):
|
353 |
-
probability = model.predict_proba(input_scaled)[0].tolist()
|
354 |
-
probability = [float(p) for p in probability]
|
355 |
-
|
356 |
-
return jsonify({
|
357 |
-
'success': True,
|
358 |
-
'prediction': user_friendly_prediction,
|
359 |
-
'probability': probability
|
360 |
-
})
|
361 |
except Exception as e:
|
362 |
-
|
363 |
-
return jsonify({'success': False, 'error': str(e)})
|
|
|
1 |
+
from flask import Blueprint, render_template, request, jsonify, redirect, url_for, flash
|
2 |
import pandas as pd
|
3 |
import numpy as np
|
|
|
|
|
|
|
|
|
|
|
|
|
4 |
from sklearn.model_selection import train_test_split
|
5 |
from sklearn.preprocessing import StandardScaler, LabelEncoder
|
6 |
from sklearn.ensemble import RandomForestClassifier
|
|
|
9 |
|
10 |
supply_failure_bp = Blueprint('supply_failure', __name__, url_prefix='/predict/supply_failure')
|
11 |
|
12 |
+
# --- Global variables for supply module (simple logic) ---
|
13 |
+
_current_df_supply = None
|
14 |
+
_model_supply = None
|
15 |
+
_scaler_supply = None
|
16 |
+
_encoders_supply = None
|
17 |
+
_feature_names_supply = None
|
18 |
+
_original_cols_supply = None
|
19 |
+
_target_col_supply = 'failure_flag' # This is fixed for the supply module
|
20 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
21 |
|
22 |
def get_summary_stats_supply(df):
|
23 |
+
"""Helper function to get summary statistics."""
|
24 |
return {
|
25 |
'total_rows': len(df),
|
26 |
'total_columns': len(df.columns),
|
|
|
31 |
}
|
32 |
|
33 |
def preprocess_data_supply(df, for_prediction=False, label_encoders=None):
|
34 |
+
"""Helper function to preprocess supply chain data."""
|
35 |
df_processed = df.copy()
|
|
|
|
|
|
|
36 |
|
37 |
+
date_cols = ['order_date', 'promised_delivery_date', 'actual_delivery_date']
|
38 |
+
categorical_columns = [col for col in df_processed.columns if df_processed[col].dtype == 'object' and col not in date_cols]
|
39 |
+
|
40 |
for col in date_cols:
|
41 |
if col in df_processed.columns:
|
|
|
42 |
df_processed[col] = pd.to_datetime(df_processed[col], errors='coerce')
|
43 |
+
df_processed[f'{col}_day_of_week'] = df_processed[col].dt.dayofweek.fillna(-1)
|
44 |
+
df_processed[f'{col}_month'] = df_processed[col].dt.month.fillna(-1)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
45 |
df_processed = df_processed.drop(columns=[col])
|
46 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
47 |
current_label_encoders = {}
|
48 |
+
if not for_prediction:
|
49 |
for col in categorical_columns:
|
50 |
if col in df_processed.columns:
|
51 |
le = LabelEncoder()
|
52 |
+
df_processed[col] = le.fit_transform(df_processed[col].astype(str).fillna('missing'))
|
53 |
current_label_encoders[col] = le
|
54 |
+
else:
|
55 |
for col, le in label_encoders.items():
|
56 |
if col in df_processed.columns:
|
57 |
+
df_processed[col] = df_processed[col].astype(str).fillna('missing').apply(
|
58 |
+
lambda x: le.transform([x])[0] if x in le.classes_ else -1)
|
|
|
59 |
|
60 |
+
# Fill any remaining NaNs in numeric columns
|
61 |
+
numeric_cols = df_processed.select_dtypes(include=np.number).columns
|
62 |
+
for col in numeric_cols:
|
63 |
+
df_processed[col] = df_processed[col].fillna(0) # Fill with 0 or another sensible default
|
64 |
|
65 |
return df_processed, current_label_encoders
|
66 |
|
67 |
|
68 |
@supply_failure_bp.route('/', methods=['GET'])
|
69 |
def show_supply_failure():
|
70 |
+
"""Renders the main page for the supply failure tool."""
|
71 |
return render_template('supply_failure.html', title="Supply Failure Prediction")
|
72 |
|
73 |
+
|
74 |
@supply_failure_bp.route('/upload_file_supply', methods=['POST'])
|
75 |
def upload_file_supply():
|
76 |
+
"""Handles file upload and displays data preview."""
|
77 |
+
global _current_df_supply, _original_cols_supply
|
78 |
if 'supply_file' not in request.files:
|
79 |
flash('No file selected')
|
80 |
return redirect(url_for('supply_failure.show_supply_failure'))
|
|
|
85 |
return redirect(url_for('supply_failure.show_supply_failure'))
|
86 |
|
87 |
try:
|
88 |
+
_current_df_supply = pd.read_csv(file)
|
89 |
+
_original_cols_supply = _current_df_supply.columns.tolist()
|
90 |
+
preview_data = _current_df_supply.head().to_dict('records')
|
91 |
+
summary_stats = get_summary_stats_supply(_current_df_supply)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
92 |
|
93 |
return render_template('supply_failure.html',
|
94 |
title="Supply Failure Prediction",
|
95 |
preview_data=preview_data,
|
96 |
+
columns=_current_df_supply.columns.tolist(),
|
97 |
summary_stats=summary_stats)
|
|
|
98 |
except Exception as e:
|
99 |
flash(f'Error processing file: {str(e)}')
|
100 |
return redirect(url_for('supply_failure.show_supply_failure'))
|
101 |
|
102 |
+
|
103 |
@supply_failure_bp.route('/run_prediction', methods=['POST'])
|
104 |
def run_prediction_supply():
|
105 |
+
"""Trains the model and returns performance metrics."""
|
106 |
+
global _current_df_supply, _model_supply, _scaler_supply, _encoders_supply, _feature_names_supply, _target_col_supply
|
107 |
+
if _current_df_supply is None:
|
108 |
+
return jsonify({'success': False, 'error': 'No data available. Please upload a CSV file first.'})
|
|
|
|
|
109 |
|
110 |
+
try:
|
111 |
+
df_processed, label_encoders = preprocess_data_supply(_current_df_supply.copy())
|
112 |
+
_encoders_supply = label_encoders
|
|
|
|
|
113 |
|
114 |
+
if _target_col_supply not in df_processed.columns:
|
115 |
+
return jsonify({'success': False, 'error': f"Target column '{_target_col_supply}' not found after preprocessing."})
|
116 |
|
117 |
+
X = df_processed.drop(columns=[_target_col_supply])
|
118 |
+
y = df_processed[_target_col_supply]
|
119 |
+
_feature_names_supply = X.columns.tolist()
|
120 |
|
121 |
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
|
122 |
+
|
123 |
+
_scaler_supply = StandardScaler()
|
124 |
+
X_train_scaled = _scaler_supply.fit_transform(X_train)
|
125 |
+
X_test_scaled = _scaler_supply.transform(X_test)
|
126 |
+
|
127 |
+
_model_supply = RandomForestClassifier(random_state=42)
|
128 |
+
_model_supply.fit(X_train_scaled, y_train)
|
129 |
+
y_pred = _model_supply.predict(X_test_scaled)
|
130 |
+
|
131 |
+
importances = _model_supply.feature_importances_
|
132 |
+
feature_importance = sorted(zip(_feature_names_supply, importances), key=lambda x: x[1], reverse=True)[:5]
|
|
|
|
|
|
|
|
|
|
|
133 |
top_features = [{'feature': f, 'importance': float(imp)} for f, imp in feature_importance]
|
134 |
|
|
|
|
|
|
|
135 |
metrics = {
|
136 |
'Accuracy': accuracy_score(y_test, y_pred),
|
137 |
'Precision': precision_score(y_test, y_pred, average='weighted', zero_division=0),
|
|
|
139 |
'F1 Score': f1_score(y_test, y_pred, average='weighted', zero_division=0)
|
140 |
}
|
141 |
|
142 |
+
return jsonify({'success': True, 'metrics': metrics, 'top_features': top_features})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
143 |
except Exception as e:
|
144 |
+
return jsonify({'success': False, 'error': f'An error occurred: {str(e)}'})
|
|
|
145 |
|
146 |
@supply_failure_bp.route('/get_form_data', methods=['GET'])
|
147 |
def get_form_data_supply():
|
148 |
+
"""Generates the fields for the single prediction form."""
|
149 |
+
if _current_df_supply is None:
|
150 |
+
return jsonify({'success': False, 'error': 'No data available. Please upload a file first.'})
|
151 |
+
|
152 |
+
df = _current_df_supply
|
153 |
+
exclude_cols = [
|
154 |
+
'delivery_delay_days', 'delivered_quantity', 'return_reason',
|
155 |
+
'delivery_status', 'failure_type', _target_col_supply, 'order_id',
|
156 |
+
'component_id', 'po_approval_delay_days', 'customs_clearance_days',
|
157 |
+
'actual_delivery_date'
|
158 |
+
]
|
159 |
+
form_fields = []
|
160 |
+
|
161 |
+
for col in df.columns:
|
162 |
+
if col.lower() in [ec.lower() for ec in exclude_cols]:
|
163 |
+
continue
|
164 |
+
|
165 |
+
field_info = {'name': col}
|
166 |
+
if pd.api.types.is_numeric_dtype(df[col]):
|
167 |
+
field_info['type'] = 'number'
|
168 |
+
field_info['default_value'] = round(df[col].mean(), 2) if not df[col].empty else 0
|
169 |
+
elif col in ['order_date', 'promised_delivery_date']:
|
170 |
+
field_info['type'] = 'text'
|
171 |
+
field_info['placeholder'] = 'YYYY-MM-DD'
|
172 |
+
field_info['default_value'] = pd.to_datetime(df[col].mode()[0]).strftime('%Y-%m-%d') if not df[col].mode().empty else ''
|
173 |
+
else:
|
174 |
+
field_info['type'] = 'select'
|
175 |
+
field_info['options'] = [str(x) for x in df[col].dropna().unique().tolist()]
|
176 |
+
field_info['default_value'] = df[col].mode()[0] if not df[col].mode().empty else ''
|
177 |
+
form_fields.append(field_info)
|
178 |
+
|
179 |
+
return jsonify({'success': True, 'form_fields': form_fields})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
180 |
|
181 |
|
182 |
@supply_failure_bp.route('/predict_single', methods=['POST'])
|
183 |
def predict_single_supply():
|
184 |
+
"""Makes a prediction for a single instance of data."""
|
185 |
+
if not all([_model_supply, _scaler_supply, _encoders_supply, _feature_names_supply, _original_cols_supply]):
|
186 |
+
return jsonify({'success': False, 'error': 'Model or configuration not ready. Please run a prediction first.'})
|
187 |
+
|
188 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
189 |
input_data = request.json
|
190 |
+
input_df = pd.DataFrame([input_data], columns=_original_cols_supply)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
191 |
|
192 |
+
preprocessed_df, _ = preprocess_data_supply(input_df.copy(), for_prediction=True, label_encoders=_encoders_supply)
|
193 |
|
194 |
+
final_features = pd.DataFrame(columns=_feature_names_supply)
|
195 |
+
final_features = pd.concat([final_features, preprocessed_df], ignore_index=True).fillna(0)
|
|
|
|
|
|
|
|
|
|
|
196 |
|
197 |
+
input_scaled = _scaler_supply.transform(final_features[_feature_names_supply])
|
198 |
|
199 |
+
prediction = _model_supply.predict(input_scaled)[0]
|
200 |
+
prediction_display = "Delivery Failed" if prediction == 1 else "Delivery Successful"
|
201 |
|
202 |
+
probability = _model_supply.predict_proba(input_scaled)[0].tolist()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
203 |
|
204 |
+
return jsonify({'success': True, 'prediction': prediction_display, 'probability': probability})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
205 |
except Exception as e:
|
206 |
+
return jsonify({'success': False, 'error': f'An error occurred during prediction: {str(e)}'})
|
|