Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -12,6 +12,9 @@ from reportlab.lib.pagesizes import letter
|
|
| 12 |
from reportlab.pdfgen import canvas
|
| 13 |
from reportlab.lib.utils import simpleSplit
|
| 14 |
from io import BytesIO
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
# Hardcoded mappings
|
| 17 |
weather_map = {"Cloudy": 0, "Rainy": 1, "Sunny": 2}
|
|
@@ -62,7 +65,46 @@ except Exception as e:
|
|
| 62 |
print(f"Error training model: {e}")
|
| 63 |
raise
|
| 64 |
|
| 65 |
-
# Function to generate
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
def generate_pdf_report(phase, weather, absentee_pct, delay_log, prediction, risk, insight):
|
| 67 |
print("Generating PDF report...")
|
| 68 |
try:
|
|
@@ -83,7 +125,7 @@ def generate_pdf_report(phase, weather, absentee_pct, delay_log, prediction, ris
|
|
| 83 |
f"Previous Delay Log: {delay_log}",
|
| 84 |
f"Predicted Delay: {prediction}%",
|
| 85 |
f"Risk Level: {risk}",
|
| 86 |
-
|
| 87 |
]
|
| 88 |
|
| 89 |
# Wrap and draw each line properly
|
|
@@ -91,7 +133,20 @@ def generate_pdf_report(phase, weather, absentee_pct, delay_log, prediction, ris
|
|
| 91 |
lines = simpleSplit(line, 'Helvetica', 12, max_width)
|
| 92 |
for wrapped_line in lines:
|
| 93 |
c.drawString(100, y_position, wrapped_line)
|
| 94 |
-
y_position -= 16
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
|
| 96 |
c.showPage()
|
| 97 |
c.save()
|
|
@@ -108,10 +163,10 @@ def generate_pdf_report(phase, weather, absentee_pct, delay_log, prediction, ris
|
|
| 108 |
f.write(pdf_data)
|
| 109 |
print(f"PDF saved locally at: {output_path}")
|
| 110 |
|
| 111 |
-
return pdf_base64, output_path
|
| 112 |
except Exception as e:
|
| 113 |
print(f"PDF generation failed: {e}")
|
| 114 |
-
return None, None
|
| 115 |
|
| 116 |
# Main prediction function
|
| 117 |
def predict_delay(phase, weather, absentee_pct, delay_log):
|
|
@@ -132,21 +187,67 @@ def predict_delay(phase, weather, absentee_pct, delay_log):
|
|
| 132 |
prediction = model.predict(input_data)[0]
|
| 133 |
prediction = round(prediction, 2)
|
| 134 |
|
|
|
|
| 135 |
if prediction >= 75:
|
| 136 |
risk = "High Risk"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 137 |
elif prediction >= 50:
|
| 138 |
risk = "Moderate Risk"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 139 |
else:
|
| 140 |
risk = "Low Risk"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
pdf_base64, pdf_path = generate_pdf_report(phase, weather, absentee_pct, delay_log, prediction, risk, insight)
|
| 145 |
|
| 146 |
-
return prediction, risk, insight, pdf_base64, pdf_path
|
| 147 |
except Exception as e:
|
| 148 |
print(f"Prediction error: {e}")
|
| 149 |
-
return None, None, f"Error: {e}", None, None
|
| 150 |
|
| 151 |
# FastAPI for Salesforce
|
| 152 |
api_app = FastAPI()
|
|
@@ -161,7 +262,7 @@ async def predict_from_salesforce(request: Request):
|
|
| 161 |
absentee_pct = data.get("absentee_pct", 0)
|
| 162 |
delay_log = data.get("delay_log", 0)
|
| 163 |
|
| 164 |
-
prediction, risk, insight, pdf_base64, pdf_path = predict_delay(phase, weather, absentee_pct, delay_log)
|
| 165 |
|
| 166 |
if prediction is None:
|
| 167 |
return JSONResponse(status_code=500, content={"status": "error", "message": insight})
|
|
@@ -172,6 +273,7 @@ async def predict_from_salesforce(request: Request):
|
|
| 172 |
"ai_insight": insight,
|
| 173 |
"pdf_report_base64": pdf_base64 if pdf_base64 else "",
|
| 174 |
"pdf_local_path": pdf_path if pdf_path else "PDF generation failed",
|
|
|
|
| 175 |
"status": "success"
|
| 176 |
})
|
| 177 |
except Exception as e:
|
|
@@ -194,11 +296,16 @@ try:
|
|
| 194 |
|
| 195 |
def predict_and_format(phase, weather, absentee, delay_log):
|
| 196 |
print("Gradio predict button clicked.")
|
| 197 |
-
prediction, risk, insight, pdf_base64, pdf_path = predict_delay(phase, weather, absentee, delay_log)
|
| 198 |
if prediction is None:
|
| 199 |
return f"Error: {insight}"
|
| 200 |
-
return f"Predicted Delay: {prediction}%\
|
| 201 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 202 |
submit.click(
|
| 203 |
predict_and_format,
|
| 204 |
inputs=[phase_input, weather_input, absentee_input, delay_input],
|
|
|
|
| 12 |
from reportlab.pdfgen import canvas
|
| 13 |
from reportlab.lib.utils import simpleSplit
|
| 14 |
from io import BytesIO
|
| 15 |
+
import matplotlib.pyplot as plt
|
| 16 |
+
import seaborn as sns
|
| 17 |
+
import numpy as np
|
| 18 |
|
| 19 |
# Hardcoded mappings
|
| 20 |
weather_map = {"Cloudy": 0, "Rainy": 1, "Sunny": 2}
|
|
|
|
| 65 |
print(f"Error training model: {e}")
|
| 66 |
raise
|
| 67 |
|
| 68 |
+
# Function to generate heatmap and return path
|
| 69 |
+
def generate_heatmap(phase, weather, model):
|
| 70 |
+
print("Generating heatmap...")
|
| 71 |
+
try:
|
| 72 |
+
# Prepare data for heatmap
|
| 73 |
+
absentee_range = np.linspace(0, 100, 20)
|
| 74 |
+
delay_log_range = np.linspace(0, 20, 20)
|
| 75 |
+
framing = 1 if phase == "Framing" else 0
|
| 76 |
+
foundation = 1 if phase == "Foundation" else 0
|
| 77 |
+
weather_encoded = weather_map.get(weather, 0)
|
| 78 |
+
|
| 79 |
+
# Generate predictions for heatmap
|
| 80 |
+
Z = np.zeros((len(delay_log_range), len(absentee_range)))
|
| 81 |
+
for i, delay_log in enumerate(delay_log_range):
|
| 82 |
+
for j, absentee in enumerate(absentee_range):
|
| 83 |
+
input_data = [[framing, foundation, weather_encoded, absentee, delay_log]]
|
| 84 |
+
Z[i, j] = model.predict(input_data)[0]
|
| 85 |
+
|
| 86 |
+
# Create heatmap
|
| 87 |
+
plt.figure(figsize=(8, 6))
|
| 88 |
+
sns.heatmap(Z, xticklabels=np.round(absentee_range, 1), yticklabels=np.round(delay_log_range, 1),
|
| 89 |
+
cmap="YlOrRd", annot=True, fmt=".1f", cbar_kws={'label': 'Predicted Delay %'})
|
| 90 |
+
plt.xlabel("Absentee %")
|
| 91 |
+
plt.ylabel("Previous Delay Log")
|
| 92 |
+
plt.title(f"Delay Prediction Heatmap (Phase: {phase}, Weather: {weather})")
|
| 93 |
+
|
| 94 |
+
# Save heatmap
|
| 95 |
+
output_dir = "pdf_reports"
|
| 96 |
+
os.makedirs(output_dir, exist_ok=True)
|
| 97 |
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 98 |
+
heatmap_path = os.path.join(output_dir, f"heatmap_{timestamp}.png")
|
| 99 |
+
plt.savefig(heatmap_path, bbox_inches='tight')
|
| 100 |
+
plt.close()
|
| 101 |
+
print(f"Heatmap saved at: {heatmap_path}")
|
| 102 |
+
return heatmap_path
|
| 103 |
+
except Exception as e:
|
| 104 |
+
print(f"Heatmap generation failed: {e}")
|
| 105 |
+
return None
|
| 106 |
+
|
| 107 |
+
# Function to generate simple PDF with heatmap and return base64-encoded string
|
| 108 |
def generate_pdf_report(phase, weather, absentee_pct, delay_log, prediction, risk, insight):
|
| 109 |
print("Generating PDF report...")
|
| 110 |
try:
|
|
|
|
| 125 |
f"Previous Delay Log: {delay_log}",
|
| 126 |
f"Predicted Delay: {prediction}%",
|
| 127 |
f"Risk Level: {risk}",
|
| 128 |
+
"AI Insight:"
|
| 129 |
]
|
| 130 |
|
| 131 |
# Wrap and draw each line properly
|
|
|
|
| 133 |
lines = simpleSplit(line, 'Helvetica', 12, max_width)
|
| 134 |
for wrapped_line in lines:
|
| 135 |
c.drawString(100, y_position, wrapped_line)
|
| 136 |
+
y_position -= 16
|
| 137 |
+
|
| 138 |
+
# Wrap and draw insight (which may be long)
|
| 139 |
+
insight_lines = simpleSplit(insight, 'Helvetica', 12, max_width)
|
| 140 |
+
for wrapped_line in insight_lines:
|
| 141 |
+
c.drawString(100, y_position, wrapped_line)
|
| 142 |
+
y_position -= 16
|
| 143 |
+
|
| 144 |
+
# Add heatmap
|
| 145 |
+
heatmap_path = generate_heatmap(phase, weather, model)
|
| 146 |
+
if heatmap_path and os.path.exists(heatmap_path):
|
| 147 |
+
c.drawString(100, y_position - 20, "Delay Prediction Heatmap:")
|
| 148 |
+
c.drawImage(heatmap_path, 100, y_position - 250, width=400, height=200)
|
| 149 |
+
y_position -= 270
|
| 150 |
|
| 151 |
c.showPage()
|
| 152 |
c.save()
|
|
|
|
| 163 |
f.write(pdf_data)
|
| 164 |
print(f"PDF saved locally at: {output_path}")
|
| 165 |
|
| 166 |
+
return pdf_base64, output_path, heatmap_path
|
| 167 |
except Exception as e:
|
| 168 |
print(f"PDF generation failed: {e}")
|
| 169 |
+
return None, None, None
|
| 170 |
|
| 171 |
# Main prediction function
|
| 172 |
def predict_delay(phase, weather, absentee_pct, delay_log):
|
|
|
|
| 187 |
prediction = model.predict(input_data)[0]
|
| 188 |
prediction = round(prediction, 2)
|
| 189 |
|
| 190 |
+
# Tailored AI Insights
|
| 191 |
if prediction >= 75:
|
| 192 |
risk = "High Risk"
|
| 193 |
+
insight = f"High delay risk ({prediction}%) in {phase} phase under {weather} conditions. "
|
| 194 |
+
if absentee_pct > 30:
|
| 195 |
+
insight += f"High absenteeism ({absentee_pct}%) is a major factor. Hire temporary workers or offer overtime incentives. "
|
| 196 |
+
else:
|
| 197 |
+
insight += f"Absenteeism ({absentee_pct}%) is moderate; ensure key staff are present for critical {phase} tasks. "
|
| 198 |
+
if delay_log > 5:
|
| 199 |
+
insight += f"Significant past delays ({delay_log}) detected; conduct a root cause analysis to address bottlenecks. "
|
| 200 |
+
else:
|
| 201 |
+
insight += f"Past delays ({delay_log}) are manageable; review task dependencies to prevent escalation. "
|
| 202 |
+
if weather == "Rainy":
|
| 203 |
+
insight += "Rainy weather increases risk; use protective coverings or shift to indoor tasks."
|
| 204 |
+
elif weather == "Cloudy":
|
| 205 |
+
insight += "Cloudy weather may slow progress; monitor conditions and prepare for potential rain."
|
| 206 |
+
else:
|
| 207 |
+
insight += "Sunny weather is optimal; maximize outdoor work to reduce delays."
|
| 208 |
elif prediction >= 50:
|
| 209 |
risk = "Moderate Risk"
|
| 210 |
+
insight = f"Moderate delay risk ({prediction}%) in {phase} phase under {weather} conditions. "
|
| 211 |
+
if absentee_pct > 30:
|
| 212 |
+
insight += f"High absenteeism ({absentee_pct}%) needs attention; consider cross-training staff to cover gaps. "
|
| 213 |
+
elif absentee_pct < 10:
|
| 214 |
+
insight += f"Low absenteeism ({absentee_pct}%) is good; maintain attendance with morale-boosting measures. "
|
| 215 |
+
else:
|
| 216 |
+
insight += f"Moderate absenteeism ({absentee_pct}%) suggests reviewing workforce allocation for {phase} tasks. "
|
| 217 |
+
if delay_log > 5:
|
| 218 |
+
insight += f"Past delays ({delay_log}) indicate inefficiencies; streamline workflows in {phase}. "
|
| 219 |
+
else:
|
| 220 |
+
insight += f"Past delays ({delay_log}) are low; ensure timely material delivery to maintain progress. "
|
| 221 |
+
if weather == "Rainy":
|
| 222 |
+
insight += "Rainy weather may disrupt work; schedule flexible tasks and secure equipment."
|
| 223 |
+
elif weather == "Cloudy":
|
| 224 |
+
insight += "Cloudy weather is manageable; keep weather monitoring active."
|
| 225 |
+
else:
|
| 226 |
+
insight += "Sunny weather supports progress; optimize daily schedules to leverage good conditions."
|
| 227 |
else:
|
| 228 |
risk = "Low Risk"
|
| 229 |
+
insight = f"Low delay risk ({prediction}%) in {phase} phase under {weather} conditions. "
|
| 230 |
+
if absentee_pct > 30:
|
| 231 |
+
insight += f"Despite low risk, high absenteeism ({absentee_pct}%) could escalate; monitor attendance closely. "
|
| 232 |
+
else:
|
| 233 |
+
insight += f"Absenteeism ({absentee_pct}%) is under control; sustain with regular team check-ins. "
|
| 234 |
+
if delay_log > 5:
|
| 235 |
+
insight += f"Past delays ({delay_log}) are notable; maintain vigilance to prevent recurrence in {phase}. "
|
| 236 |
+
else:
|
| 237 |
+
insight += f"Minimal past delays ({delay_log}); continue efficient task management in {phase}. "
|
| 238 |
+
if weather == "Rainy":
|
| 239 |
+
insight += "Rainy weather could pose minor risks; have contingency plans ready."
|
| 240 |
+
elif weather == "Cloudy":
|
| 241 |
+
insight += "Cloudy weather is unlikely to cause issues; maintain standard operations."
|
| 242 |
+
else:
|
| 243 |
+
insight += "Sunny weather is ideal; capitalize on it to stay ahead of schedule."
|
| 244 |
|
| 245 |
+
pdf_base64, pdf_path, heatmap_path = generate_pdf_report(phase, weather, absentee_pct, delay_log, prediction, risk, insight)
|
|
|
|
|
|
|
| 246 |
|
| 247 |
+
return prediction, risk, insight, pdf_base64, pdf_path, heatmap_path
|
| 248 |
except Exception as e:
|
| 249 |
print(f"Prediction error: {e}")
|
| 250 |
+
return None, None, f"Error: {e}", None, None, None
|
| 251 |
|
| 252 |
# FastAPI for Salesforce
|
| 253 |
api_app = FastAPI()
|
|
|
|
| 262 |
absentee_pct = data.get("absentee_pct", 0)
|
| 263 |
delay_log = data.get("delay_log", 0)
|
| 264 |
|
| 265 |
+
prediction, risk, insight, pdf_base64, pdf_path, heatmap_path = predict_delay(phase, weather, absentee_pct, delay_log)
|
| 266 |
|
| 267 |
if prediction is None:
|
| 268 |
return JSONResponse(status_code=500, content={"status": "error", "message": insight})
|
|
|
|
| 273 |
"ai_insight": insight,
|
| 274 |
"pdf_report_base64": pdf_base64 if pdf_base64 else "",
|
| 275 |
"pdf_local_path": pdf_path if pdf_path else "PDF generation failed",
|
| 276 |
+
"heatmap_path": heatmap_path if heatmap_path else "Heatmap generation failed",
|
| 277 |
"status": "success"
|
| 278 |
})
|
| 279 |
except Exception as e:
|
|
|
|
| 296 |
|
| 297 |
def predict_and_format(phase, weather, absentee, delay_log):
|
| 298 |
print("Gradio predict button clicked.")
|
| 299 |
+
prediction, risk, insight, pdf_base64, pdf_path, heatmap_path = predict_delay(phase, weather, absentee, delay_log)
|
| 300 |
if prediction is None:
|
| 301 |
return f"Error: {insight}"
|
| 302 |
+
return (f"Predicted Delay: {prediction}%\n"
|
| 303 |
+
f"Risk Level: {risk}\n"
|
| 304 |
+
f"Insight: {insight}\n"
|
| 305 |
+
f"PDF Report: {'Saved locally at ' + pdf_path if pdf_path else 'Failed to generate'}\n"
|
| 306 |
+
f"Heatmap: {'Saved locally at ' + heatmap_path if heatmap_path else 'Failed to generate'}\n"
|
| 307 |
+
f"PDF Base64: {'Generated' if pdf_base64 else 'Not generated'}")
|
| 308 |
+
|
| 309 |
submit.click(
|
| 310 |
predict_and_format,
|
| 311 |
inputs=[phase_input, weather_input, absentee_input, delay_input],
|