AjaykumarPilla commited on
Commit
4b82103
·
verified ·
1 Parent(s): eb203e0

Upload 3 files

Browse files
Files changed (3) hide show
  1. app.py +186 -0
  2. model.py +131 -0
  3. utils.py +36 -0
app.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import matplotlib.pyplot as plt
4
+ from datetime import datetime
5
+ from model import predict_delay, get_weather_condition
6
+ from utils import validate_inputs, generate_heatmap
7
+ from reportlab.lib.pagesizes import letter
8
+ from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image
9
+ from reportlab.lib.styles import getSampleStyleSheet
10
+ from reportlab.lib.units import inch
11
+ from io import BytesIO
12
+
13
+ # Streamlit app configuration
14
+ st.set_page_config(page_title="Delay 🚀", layout="wide")
15
+
16
+ # Title
17
+ st.title("Project Delay Predictor 🚀")
18
+
19
+ # Task options per phase
20
+ task_options = {
21
+ "Planning": ["Define Scope", "Resource Allocation", "Permit Acquisition"],
22
+ "Design": ["Architectural Drafting", "Engineering Analysis", "Design Review"],
23
+ "Construction": ["Foundation Work", "Structural Build", "Utility Installation"]
24
+ }
25
+
26
+ # Initialize session state for phase and task
27
+ if 'phase' not in st.session_state:
28
+ st.session_state.phase = ""
29
+ if 'task' not in st.session_state:
30
+ st.session_state.task = ""
31
+
32
+ # Function to format high_risk_phases with flag and alert
33
+ def format_high_risk_phases(high_risk_phases):
34
+ formatted = []
35
+ for phase in high_risk_phases:
36
+ flag = "🚩" if phase['risk'] > 75 else ""
37
+ alert = "[Alert]" if phase['risk'] > 75 else ""
38
+ formatted.append(f"{flag} {phase['phase']}: {phase['task']} (Risk: {phase['risk']:.1f}%) {alert}")
39
+ return formatted
40
+
41
+ # Function to generate PDF
42
+ def generate_pdf(input_data, prediction, heatmap_fig):
43
+ buffer = BytesIO()
44
+ doc = SimpleDocTemplate(buffer, pagesize=letter)
45
+ styles = getSampleStyleSheet()
46
+ story = []
47
+
48
+ # Title
49
+ story.append(Paragraph("Project Delay Prediction Report", styles['Title']))
50
+ story.append(Spacer(1, 12))
51
+
52
+ # Input Data
53
+ story.append(Paragraph("Input Data", styles['Heading2']))
54
+ input_fields = [
55
+ f"Project Name: {input_data['project_name']}",
56
+ f"Phase: {input_data['phase']}",
57
+ f"Task: {input_data['task']}",
58
+ f"Current Progress: {input_data['current_progress']}%",
59
+ f"Task Expected Duration: {input_data['task_expected_duration']} days",
60
+ f"Task Actual Duration: {input_data['task_actual_duration']} days",
61
+ f"Workforce Gap: {input_data['workforce_gap']}%",
62
+ f"Workforce Skill Level: {input_data['workforce_skill_level']}",
63
+ f"Workforce Shift Hours: {input_data['workforce_shift_hours']}",
64
+ f"Weather Impact Score: {input_data['weather_impact_score']}",
65
+ f"Weather Condition: {input_data['weather_condition']}",
66
+ f"Weather Forecast Date: {input_data['weather_forecast_date']}"
67
+ ]
68
+ for field in input_fields:
69
+ story.append(Paragraph(field, styles['Normal']))
70
+ story.append(Spacer(1, 12))
71
+
72
+ # Prediction Results
73
+ story.append(Paragraph("Prediction Results", styles['Heading2']))
74
+ # Format high_risk_phases for PDF
75
+ high_risk_text = "<br/>".join(format_high_risk_phases(prediction['high_risk_phases']))
76
+ prediction_fields = [
77
+ f"Delay Probability: {prediction['delay_probability']:.2f}%",
78
+ f"High Risk Phases:<br/>{high_risk_text}",
79
+ f"AI Insights: {prediction['ai_insights']}",
80
+ f"Weather Condition: {prediction['weather_condition']}"
81
+ ]
82
+ for field in prediction_fields:
83
+ story.append(Paragraph(field, styles['Normal']))
84
+ story.append(Spacer(1, 12))
85
+
86
+ # Heatmap
87
+ story.append(Paragraph("Delay Risk Heatmap", styles['Heading2']))
88
+ # Save heatmap figure to BytesIO as PNG
89
+ img_buffer = BytesIO()
90
+ heatmap_fig.savefig(img_buffer, format='png', bbox_inches='tight')
91
+ img_buffer.seek(0)
92
+ # Embed image in PDF (scale to fit page width)
93
+ story.append(Image(img_buffer, width=6*inch, height=2*inch))
94
+ plt.close(heatmap_fig) # Close figure to free memory
95
+
96
+ doc.build(story)
97
+ buffer.seek(0)
98
+ return buffer
99
+
100
+ # Input form
101
+ with st.form("project_form"):
102
+ col1, col2 = st.columns(2)
103
+
104
+ with col1:
105
+ project_name = st.text_input("Project Name")
106
+ phase = st.selectbox("Phase", [""] + ["Planning", "Design", "Construction"], index=0, key="phase_select")
107
+
108
+ # Update task options based on phase
109
+ if phase != st.session_state.phase:
110
+ st.session_state.phase = phase
111
+ st.session_state.task = "" # Reset task when phase changes
112
+ task_options_list = [""] + task_options.get(phase, []) if phase else [""]
113
+ task = st.selectbox("Task", task_options_list, index=0, key="task_select")
114
+ current_progress = st.number_input("Current Progress (%)", min_value=0.0, max_value=100.0, step=1.0)
115
+ task_expected_duration = st.number_input("Task Expected Duration (days)", min_value=0, step=1)
116
+ task_actual_duration = st.number_input("Task Actual Duration (days)", min_value=0, step=1)
117
+
118
+ with col2:
119
+ workforce_gap = st.number_input("Workforce Gap (%)", min_value=0.0, max_value=100.0, step=1.0)
120
+ workforce_skill_level = st.selectbox("Workforce Skill Level", ["Low", "Medium", "High"], index=1)
121
+ workforce_shift_hours = st.number_input("Workforce Shift Hours", min_value=0, step=1, value=8)
122
+ # Debug output for shift hours
123
+ st.write(f"**Selected Shift Hours**: {workforce_shift_hours}")
124
+ weather_impact_score = st.number_input("Weather Impact Score (0-100)", min_value=0, max_value=100, step=1)
125
+ # Display computed weather condition
126
+ weather_condition = get_weather_condition(weather_impact_score)
127
+ st.write(f"**Weather Condition**: {weather_condition}")
128
+ weather_forecast_date = st.date_input("Weather Forecast Date", min_value=datetime(2025, 1, 1))
129
+
130
+ submit_button = st.form_submit_button("Predict Delay")
131
+
132
+ # Process form submission
133
+ if submit_button:
134
+ # Prepare input data
135
+ input_data = {
136
+ "project_name": project_name,
137
+ "phase": phase,
138
+ "task": task,
139
+ "current_progress": current_progress,
140
+ "task_expected_duration": task_expected_duration,
141
+ "task_actual_duration": task_actual_duration,
142
+ "workforce_gap": workforce_gap,
143
+ "workforce_skill_level": workforce_skill_level,
144
+ "workforce_shift_hours": workforce_shift_hours,
145
+ "weather_impact_score": weather_impact_score,
146
+ "weather_condition": weather_condition,
147
+ "weather_forecast_date": weather_forecast_date.strftime("%Y-%m-%d")
148
+ }
149
+
150
+ # Validate inputs
151
+ error = validate_inputs(input_data)
152
+ if error:
153
+ st.error(error)
154
+ else:
155
+ # Get prediction
156
+ with st.spinner("Predicting..."):
157
+ prediction = predict_delay(input_data)
158
+
159
+ if "error" in prediction:
160
+ st.error(prediction["error"])
161
+ else:
162
+ # Display results
163
+ st.subheader("Prediction Results")
164
+ st.write(f"**Delay Probability**: {prediction['delay_probability']:.2f}%")
165
+ st.write("**High Risk Phases**:")
166
+ for line in format_high_risk_phases(prediction['high_risk_phases']):
167
+ st.write(line)
168
+ st.write(f"**AI Insights**: {prediction['ai_insights']}")
169
+ st.write(f"**Weather Condition**: {prediction['weather_condition']}")
170
+
171
+ # Generate and display heatmap
172
+ fig = generate_heatmap(prediction['delay_probability'], f"{phase}: {task}")
173
+ st.pyplot(fig)
174
+
175
+ # Generate PDF with heatmap and provide download link
176
+ pdf_buffer = generate_pdf(input_data, prediction, fig)
177
+ st.download_button(
178
+ label="Download Prediction Report (PDF)",
179
+ data=pdf_buffer,
180
+ file_name="project_delay_report.pdf",
181
+ mime="application/pdf"
182
+ )
183
+
184
+ # Store prediction in session state
185
+ st.session_state.prediction = prediction
186
+ st.session_state.input_data = input_data
model.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ def get_weather_condition(score):
2
+ """Map weather impact score (0-100) to descriptive weather condition."""
3
+ if score <= 10:
4
+ return "Sunny"
5
+ elif score <= 30:
6
+ return "Partly Cloudy"
7
+ elif score <= 50:
8
+ return "Cloudy"
9
+ elif score <= 70:
10
+ return "Light Rain"
11
+ elif score <= 85:
12
+ return "Heavy Rain"
13
+ else:
14
+ return "Severe Storm"
15
+
16
+ def predict_delay(input_data):
17
+ """
18
+ Predict delay probability based on project task data.
19
+ Uses task duration, progress, workforce info, and weather impact.
20
+ """
21
+ phase = input_data.get("phase", "")
22
+ task = input_data.get("task", "")
23
+ expected_duration = input_data.get("task_expected_duration", 0)
24
+ actual_duration = input_data.get("task_actual_duration", 0)
25
+
26
+ current_progress = input_data.get("current_progress", 0) # in %
27
+ workforce_gap_pct = input_data.get("workforce_gap", 0) # in %
28
+ skill_level = input_data.get("workforce_skill_level", "").lower()
29
+ shift_hours = input_data.get("workforce_shift_hours", 0)
30
+ weather_score = input_data.get("weather_impact_score", 0) # 0-100 scale
31
+
32
+ # Auto-set weather condition if missing or inconsistent
33
+ weather_condition = input_data.get("weather_condition", "")
34
+ if not weather_condition:
35
+ weather_condition = get_weather_condition(weather_score)
36
+
37
+ # Task options for phase (hardcoded to match app.py)
38
+ task_options = {
39
+ "Planning": ["Define Scope", "Resource Allocation", "Permit Acquisition"],
40
+ "Design": ["Architectural Drafting", "Engineering Analysis", "Design Review"],
41
+ "Construction": ["Foundation Work", "Structural Build", "Utility Installation"]
42
+ }
43
+
44
+ delay_risk = 0
45
+ insights = []
46
+
47
+ # 1. Duration overrun risk
48
+ if expected_duration > 0 and actual_duration > expected_duration:
49
+ overrun_pct = ((actual_duration - expected_duration) / expected_duration) * 100
50
+ delay_risk += min(overrun_pct, 30)
51
+ insights.append(f"Actual duration is {overrun_pct:.1f}% over expected.")
52
+
53
+ # 2. Progress lag risk
54
+ if expected_duration > 0 and current_progress >= 0:
55
+ expected_progress = (actual_duration / expected_duration) * 100
56
+ if current_progress < expected_progress:
57
+ progress_gap = expected_progress - current_progress
58
+ delay_risk += min(progress_gap, 25)
59
+ insights.append(f"Current progress ({current_progress}%) lags behind expected ({expected_progress:.1f}%).")
60
+
61
+ # 3. Workforce gap impact
62
+ if workforce_gap_pct > 0:
63
+ delay_risk += min(workforce_gap_pct * 0.5, 20)
64
+ insights.append(f"Workforce gap at {workforce_gap_pct}% reduces productivity.")
65
+
66
+ # 4. Skill level effect
67
+ if skill_level == "low":
68
+ delay_risk += 15
69
+ insights.append("Low skill level may reduce task efficiency.")
70
+ elif skill_level == "medium":
71
+ delay_risk += 7
72
+
73
+ # 5. Shift hours effect
74
+ if shift_hours < 8:
75
+ penalty = (8 - shift_hours) * 3
76
+ delay_risk += penalty
77
+ insights.append(f"Reduced shift hours ({shift_hours}h) add {penalty:.1f}% to delay risk.")
78
+ elif shift_hours > 8:
79
+ bonus = (shift_hours - 8) * 2
80
+ delay_risk -= min(bonus, 10)
81
+ insights.append(f"Extended shift hours ({shift_hours}h) reduce delay risk by {min(bonus, 10):.1f}%.")
82
+ else:
83
+ insights.append("Standard shift hours (8h) have neutral impact.")
84
+
85
+ # 6. Weather impact effect
86
+ if weather_score > 50:
87
+ delay_risk += min(weather_score / 2, 20)
88
+ insights.append(f"High weather impact score ({weather_score}) — current condition: {weather_condition}.")
89
+
90
+ # Ensure delay_risk is between 0 and 100
91
+ delay_risk = max(0, min(delay_risk, 100))
92
+
93
+ # Generate high_risk_phases for all tasks in the phase
94
+ high_risk_phases = []
95
+ if phase in task_options:
96
+ for t in task_options[phase]:
97
+ task_risk = delay_risk
98
+ # Adjust risk slightly for other tasks (simulate variation)
99
+ if t != task:
100
+ task_risk = min(max(task_risk + (hash(t) % 10 - 5), 0), 100) # ±5% variation
101
+ high_risk_phases.append({
102
+ "phase": phase,
103
+ "task": t,
104
+ "risk": round(task_risk, 1)
105
+ })
106
+
107
+ # Enhanced mitigation strategies based on risk level
108
+ mitigation_strategies = []
109
+ if delay_risk > 75:
110
+ mitigation_strategies.append("Urgent: Allocate additional resources and expedite critical tasks.")
111
+ if phase == "Construction":
112
+ mitigation_strategies.append("Secure backup equipment and materials to counter weather delays.")
113
+ elif phase == "Planning":
114
+ mitigation_strategies.append("Fast-track permit approvals and stakeholder alignment.")
115
+ elif delay_risk > 50:
116
+ mitigation_strategies.append("Moderate risk: Increase workforce or extend shift hours.")
117
+ if weather_score > 50:
118
+ mitigation_strategies.append("Plan indoor tasks or weather-resistant schedules.")
119
+ else:
120
+ mitigation_strategies.append("Low risk: Maintain current plan, monitor progress closely.")
121
+ insights.extend(mitigation_strategies)
122
+
123
+ return {
124
+ "project": input_data.get("project_name", "Unnamed Project"),
125
+ "phase": phase,
126
+ "task": task,
127
+ "delay_probability": round(delay_risk, 1),
128
+ "ai_insights": "; ".join(insights) if insights else "No significant delay factors detected.",
129
+ "high_risk_phases": high_risk_phases,
130
+ "weather_condition": weather_condition
131
+ }
utils.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import matplotlib.pyplot as plt
2
+
3
+ def validate_inputs(input_data):
4
+ """
5
+ Validate input data for required fields and ranges.
6
+ """
7
+ required_fields = [
8
+ "project_name", "phase", "task", "current_progress",
9
+ "task_expected_duration", "task_actual_duration", "workforce_gap",
10
+ "workforce_shift_hours", "weather_impact_score", "weather_condition",
11
+ "weather_forecast_date"
12
+ ]
13
+ for field in required_fields:
14
+ if not input_data[field]:
15
+ return f"Please select or fill in {field.replace('_', ' ').lower()}"
16
+ if not (0 <= input_data["current_progress"] <= 100):
17
+ return "Current progress must be between 0 and 100"
18
+ if not (0 <= input_data["workforce_gap"] <= 100):
19
+ return "Workforce gap must be between 0 and 100"
20
+ if not (0 <= input_data["weather_impact_score"] <= 100):
21
+ return "Weather impact score must be between 0 and 100"
22
+ return None
23
+
24
+ def generate_heatmap(delay_probability, label):
25
+ """
26
+ Generate a bar chart to visualize delay probability.
27
+ Returns the matplotlib figure object.
28
+ """
29
+ fig, ax = plt.subplots(figsize=(8, 2))
30
+ color = 'red' if delay_probability > 75 else 'yellow' if delay_probability > 50 else 'green'
31
+ ax.barh([label], [delay_probability], color=color, edgecolor='black')
32
+ ax.set_xlim(0, 100)
33
+ ax.set_xlabel("Delay Probability (%)")
34
+ ax.set_title("Delay Risk Heatmap")
35
+ plt.tight_layout()
36
+ return fig