Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -17,7 +17,6 @@ import matplotlib.pyplot as plt
|
|
| 17 |
import seaborn as sns
|
| 18 |
import numpy as np
|
| 19 |
|
| 20 |
-
# Hugging Face transformers pipeline import
|
| 21 |
from transformers import pipeline
|
| 22 |
|
| 23 |
weather_map = {"Cloudy": 0, "Rainy": 1, "Sunny": 2}
|
|
@@ -36,11 +35,11 @@ try:
|
|
| 36 |
df = pd.DataFrame(default_data)
|
| 37 |
else:
|
| 38 |
df = pd.read_csv("new_delay_data.csv")
|
| 39 |
-
|
| 40 |
df = pd.get_dummies(df, columns=["Phase"], drop_first=True)
|
| 41 |
df["Weather"] = df["Weather"].map(weather_map)
|
| 42 |
df.dropna(subset=["Weather", "Absentee", "DelayLog", "Delay%"], inplace=True)
|
| 43 |
-
|
| 44 |
for col in ["Phase_Framing", "Phase_Foundation"]:
|
| 45 |
if col not in df.columns:
|
| 46 |
df[col] = 0
|
|
@@ -65,9 +64,9 @@ except Exception as e:
|
|
| 65 |
print(f"Error training model: {e}")
|
| 66 |
raise
|
| 67 |
|
| 68 |
-
print("Loading AI text generation model (
|
| 69 |
try:
|
| 70 |
-
text_generator = pipeline("text-generation", model="
|
| 71 |
print("Text generation model loaded successfully.")
|
| 72 |
except Exception as e:
|
| 73 |
print(f"Failed to load text generation model: {e}")
|
|
@@ -84,7 +83,8 @@ def generate_ai_insight(phase, weather, absentee_pct, delay_log, prediction):
|
|
| 84 |
f"Provide a brief insight on the delay risks and a practical migration plan to mitigate these delays."
|
| 85 |
)
|
| 86 |
try:
|
| 87 |
-
result = text_generator(prompt, max_length=
|
|
|
|
| 88 |
generated_text = result[0]['generated_text']
|
| 89 |
insight = generated_text[len(prompt):].strip()
|
| 90 |
return insight
|
|
@@ -99,20 +99,20 @@ def generate_heatmap(phase, weather, model):
|
|
| 99 |
framing = 1 if phase == "Framing" else 0
|
| 100 |
foundation = 1 if phase == "Foundation" else 0
|
| 101 |
weather_encoded = weather_map.get(weather, 0)
|
| 102 |
-
|
| 103 |
Z = np.zeros((len(delay_log_range), len(absentee_range)))
|
| 104 |
for i, delay_log in enumerate(delay_log_range):
|
| 105 |
for j, absentee in enumerate(absentee_range):
|
| 106 |
input_data = [[framing, foundation, weather_encoded, absentee, delay_log]]
|
| 107 |
Z[i, j] = model.predict(input_data)[0]
|
| 108 |
-
|
| 109 |
plt.figure(figsize=(8, 6))
|
| 110 |
sns.heatmap(Z, xticklabels=np.round(absentee_range, 1), yticklabels=np.round(delay_log_range, 1),
|
| 111 |
cmap="YlOrRd", annot=True, fmt=".1f", cbar_kws={'label': 'Predicted Delay %'})
|
| 112 |
plt.xlabel("Absentee %")
|
| 113 |
plt.ylabel("Previous Delay Log")
|
| 114 |
plt.title(f"Delay Prediction Heatmap (Phase: {phase}, Weather: {weather})")
|
| 115 |
-
|
| 116 |
output_dir = "pdf_reports"
|
| 117 |
os.makedirs(output_dir, exist_ok=True)
|
| 118 |
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
|
@@ -128,7 +128,7 @@ def generate_pdf_report(phase, weather, absentee_pct, delay_log, prediction, ris
|
|
| 128 |
try:
|
| 129 |
buffer = BytesIO()
|
| 130 |
c = canvas.Canvas(buffer, pagesize=letter)
|
| 131 |
-
|
| 132 |
try:
|
| 133 |
pdfmetrics.registerFont(TTFont('DejaVuSans', 'DejaVuSans.ttf'))
|
| 134 |
c.setFont("DejaVuSans", 12)
|
|
@@ -137,13 +137,13 @@ def generate_pdf_report(phase, weather, absentee_pct, delay_log, prediction, ris
|
|
| 137 |
print(f"Failed to load DejaVuSans font: {e}. Falling back to Helvetica with text flag.")
|
| 138 |
c.setFont("Helvetica", 12)
|
| 139 |
flag_indicator = " [FLAG]" if prediction >= 75 else ""
|
| 140 |
-
|
| 141 |
c.drawString(100, 750, "Project Delay Prediction Report")
|
| 142 |
c.drawString(100, 730, f"Generated on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
|
| 143 |
-
|
| 144 |
y_position = 700
|
| 145 |
max_width = 400
|
| 146 |
-
|
| 147 |
details = [
|
| 148 |
f"Phase: {phase}",
|
| 149 |
f"Weather: {weather}",
|
|
@@ -153,38 +153,38 @@ def generate_pdf_report(phase, weather, absentee_pct, delay_log, prediction, ris
|
|
| 153 |
f"Risk Level: {risk}",
|
| 154 |
"AI Insight & Migration Plan:"
|
| 155 |
]
|
| 156 |
-
|
| 157 |
for line in details:
|
| 158 |
lines = simpleSplit(line, 'DejaVuSans' if 'DejaVuSans' in pdfmetrics.getRegisteredFontNames() else 'Helvetica', 12, max_width)
|
| 159 |
for wrapped_line in lines:
|
| 160 |
c.drawString(100, y_position, wrapped_line)
|
| 161 |
y_position -= 16
|
| 162 |
-
|
| 163 |
insight_lines = simpleSplit(insight, 'DejaVuSans' if 'DejaVuSans' in pdfmetrics.getRegisteredFontNames() else 'Helvetica', 12, max_width)
|
| 164 |
for wrapped_line in insight_lines:
|
| 165 |
c.drawString(100, y_position, wrapped_line)
|
| 166 |
y_position -= 16
|
| 167 |
-
|
| 168 |
heatmap_path = generate_heatmap(phase, weather, model)
|
| 169 |
if heatmap_path and os.path.exists(heatmap_path):
|
| 170 |
c.drawString(100, y_position - 20, "Delay Prediction Heatmap:")
|
| 171 |
c.drawImage(heatmap_path, 100, y_position - 250, width=400, height=200)
|
| 172 |
y_position -= 270
|
| 173 |
-
|
| 174 |
c.showPage()
|
| 175 |
c.save()
|
| 176 |
-
|
| 177 |
pdf_data = buffer.getvalue()
|
| 178 |
buffer.close()
|
| 179 |
pdf_base64 = base64.b64encode(pdf_data).decode("utf-8")
|
| 180 |
-
|
| 181 |
output_dir = "pdf_reports"
|
| 182 |
os.makedirs(output_dir, exist_ok=True)
|
| 183 |
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 184 |
output_path = os.path.join(output_dir, f"delay_report_{timestamp}.pdf")
|
| 185 |
with open(output_path, "wb") as f:
|
| 186 |
f.write(pdf_data)
|
| 187 |
-
|
| 188 |
return pdf_base64, output_path, heatmap_path
|
| 189 |
except Exception as e:
|
| 190 |
print(f"PDF generation failed: {e}")
|
|
@@ -274,7 +274,7 @@ try:
|
|
| 274 |
f"PDF Report: {'Saved locally at ' + pdf_path if pdf_path else 'Failed to generate'}\n"
|
| 275 |
f"Heatmap: {'Saved locally at ' + heatmap_path if heatmap_path else 'Failed to generate'}\n"
|
| 276 |
f"PDF Base64: {'Generated' if pdf_base64 else 'Not generated'}")
|
| 277 |
-
|
| 278 |
submit.click(
|
| 279 |
predict_and_format,
|
| 280 |
inputs=[phase_input, weather_input, absentee_input, delay_input],
|
|
|
|
| 17 |
import seaborn as sns
|
| 18 |
import numpy as np
|
| 19 |
|
|
|
|
| 20 |
from transformers import pipeline
|
| 21 |
|
| 22 |
weather_map = {"Cloudy": 0, "Rainy": 1, "Sunny": 2}
|
|
|
|
| 35 |
df = pd.DataFrame(default_data)
|
| 36 |
else:
|
| 37 |
df = pd.read_csv("new_delay_data.csv")
|
| 38 |
+
|
| 39 |
df = pd.get_dummies(df, columns=["Phase"], drop_first=True)
|
| 40 |
df["Weather"] = df["Weather"].map(weather_map)
|
| 41 |
df.dropna(subset=["Weather", "Absentee", "DelayLog", "Delay%"], inplace=True)
|
| 42 |
+
|
| 43 |
for col in ["Phase_Framing", "Phase_Foundation"]:
|
| 44 |
if col not in df.columns:
|
| 45 |
df[col] = 0
|
|
|
|
| 64 |
print(f"Error training model: {e}")
|
| 65 |
raise
|
| 66 |
|
| 67 |
+
print("Loading AI text generation model (distilgpt2)...")
|
| 68 |
try:
|
| 69 |
+
text_generator = pipeline("text-generation", model="distilgpt2")
|
| 70 |
print("Text generation model loaded successfully.")
|
| 71 |
except Exception as e:
|
| 72 |
print(f"Failed to load text generation model: {e}")
|
|
|
|
| 83 |
f"Provide a brief insight on the delay risks and a practical migration plan to mitigate these delays."
|
| 84 |
)
|
| 85 |
try:
|
| 86 |
+
result = text_generator(prompt, max_length=80, num_return_sequences=1,
|
| 87 |
+
temperature=0.7, top_p=0.9, early_stopping=True)
|
| 88 |
generated_text = result[0]['generated_text']
|
| 89 |
insight = generated_text[len(prompt):].strip()
|
| 90 |
return insight
|
|
|
|
| 99 |
framing = 1 if phase == "Framing" else 0
|
| 100 |
foundation = 1 if phase == "Foundation" else 0
|
| 101 |
weather_encoded = weather_map.get(weather, 0)
|
| 102 |
+
|
| 103 |
Z = np.zeros((len(delay_log_range), len(absentee_range)))
|
| 104 |
for i, delay_log in enumerate(delay_log_range):
|
| 105 |
for j, absentee in enumerate(absentee_range):
|
| 106 |
input_data = [[framing, foundation, weather_encoded, absentee, delay_log]]
|
| 107 |
Z[i, j] = model.predict(input_data)[0]
|
| 108 |
+
|
| 109 |
plt.figure(figsize=(8, 6))
|
| 110 |
sns.heatmap(Z, xticklabels=np.round(absentee_range, 1), yticklabels=np.round(delay_log_range, 1),
|
| 111 |
cmap="YlOrRd", annot=True, fmt=".1f", cbar_kws={'label': 'Predicted Delay %'})
|
| 112 |
plt.xlabel("Absentee %")
|
| 113 |
plt.ylabel("Previous Delay Log")
|
| 114 |
plt.title(f"Delay Prediction Heatmap (Phase: {phase}, Weather: {weather})")
|
| 115 |
+
|
| 116 |
output_dir = "pdf_reports"
|
| 117 |
os.makedirs(output_dir, exist_ok=True)
|
| 118 |
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
|
|
|
| 128 |
try:
|
| 129 |
buffer = BytesIO()
|
| 130 |
c = canvas.Canvas(buffer, pagesize=letter)
|
| 131 |
+
|
| 132 |
try:
|
| 133 |
pdfmetrics.registerFont(TTFont('DejaVuSans', 'DejaVuSans.ttf'))
|
| 134 |
c.setFont("DejaVuSans", 12)
|
|
|
|
| 137 |
print(f"Failed to load DejaVuSans font: {e}. Falling back to Helvetica with text flag.")
|
| 138 |
c.setFont("Helvetica", 12)
|
| 139 |
flag_indicator = " [FLAG]" if prediction >= 75 else ""
|
| 140 |
+
|
| 141 |
c.drawString(100, 750, "Project Delay Prediction Report")
|
| 142 |
c.drawString(100, 730, f"Generated on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
|
| 143 |
+
|
| 144 |
y_position = 700
|
| 145 |
max_width = 400
|
| 146 |
+
|
| 147 |
details = [
|
| 148 |
f"Phase: {phase}",
|
| 149 |
f"Weather: {weather}",
|
|
|
|
| 153 |
f"Risk Level: {risk}",
|
| 154 |
"AI Insight & Migration Plan:"
|
| 155 |
]
|
| 156 |
+
|
| 157 |
for line in details:
|
| 158 |
lines = simpleSplit(line, 'DejaVuSans' if 'DejaVuSans' in pdfmetrics.getRegisteredFontNames() else 'Helvetica', 12, max_width)
|
| 159 |
for wrapped_line in lines:
|
| 160 |
c.drawString(100, y_position, wrapped_line)
|
| 161 |
y_position -= 16
|
| 162 |
+
|
| 163 |
insight_lines = simpleSplit(insight, 'DejaVuSans' if 'DejaVuSans' in pdfmetrics.getRegisteredFontNames() else 'Helvetica', 12, max_width)
|
| 164 |
for wrapped_line in insight_lines:
|
| 165 |
c.drawString(100, y_position, wrapped_line)
|
| 166 |
y_position -= 16
|
| 167 |
+
|
| 168 |
heatmap_path = generate_heatmap(phase, weather, model)
|
| 169 |
if heatmap_path and os.path.exists(heatmap_path):
|
| 170 |
c.drawString(100, y_position - 20, "Delay Prediction Heatmap:")
|
| 171 |
c.drawImage(heatmap_path, 100, y_position - 250, width=400, height=200)
|
| 172 |
y_position -= 270
|
| 173 |
+
|
| 174 |
c.showPage()
|
| 175 |
c.save()
|
| 176 |
+
|
| 177 |
pdf_data = buffer.getvalue()
|
| 178 |
buffer.close()
|
| 179 |
pdf_base64 = base64.b64encode(pdf_data).decode("utf-8")
|
| 180 |
+
|
| 181 |
output_dir = "pdf_reports"
|
| 182 |
os.makedirs(output_dir, exist_ok=True)
|
| 183 |
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 184 |
output_path = os.path.join(output_dir, f"delay_report_{timestamp}.pdf")
|
| 185 |
with open(output_path, "wb") as f:
|
| 186 |
f.write(pdf_data)
|
| 187 |
+
|
| 188 |
return pdf_base64, output_path, heatmap_path
|
| 189 |
except Exception as e:
|
| 190 |
print(f"PDF generation failed: {e}")
|
|
|
|
| 274 |
f"PDF Report: {'Saved locally at ' + pdf_path if pdf_path else 'Failed to generate'}\n"
|
| 275 |
f"Heatmap: {'Saved locally at ' + heatmap_path if heatmap_path else 'Failed to generate'}\n"
|
| 276 |
f"PDF Base64: {'Generated' if pdf_base64 else 'Not generated'}")
|
| 277 |
+
|
| 278 |
submit.click(
|
| 279 |
predict_and_format,
|
| 280 |
inputs=[phase_input, weather_input, absentee_input, delay_input],
|