AjaykumarPilla commited on
Commit
2e0d964
·
verified ·
1 Parent(s): 7e8f8cb

Update model.py

Browse files
Files changed (1) hide show
  1. model.py +65 -32
model.py CHANGED
@@ -1,4 +1,8 @@
1
- def get_weather_condition(score):
 
 
 
 
2
  """Map weather impact score (0-100) to descriptive weather condition."""
3
  if score <= 10:
4
  return "Sunny"
@@ -13,10 +17,65 @@ def get_weather_condition(score):
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", "")
@@ -42,13 +101,11 @@ def predict_delay(input_data):
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:
@@ -56,36 +113,26 @@ def predict_delay(input_data):
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))
@@ -95,7 +142,6 @@ def predict_delay(input_data):
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({
@@ -104,21 +150,8 @@ def predict_delay(input_data):
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"),
 
1
+ from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
2
+ import torch
3
+ from typing import Dict, List
4
+
5
+ def get_weather_condition(score: int) -> str:
6
  """Map weather impact score (0-100) to descriptive weather condition."""
7
  if score <= 10:
8
  return "Sunny"
 
17
  else:
18
  return "Severe Storm"
19
 
20
+ def call_ai_model_for_insights(input_data: Dict, delay_risk: float) -> List[str]:
21
+ """
22
+ Use DistilBART in Hugging Face Space (CPU) to generate insights based on input data and delay risk.
23
+ """
24
+ model_name = "sshleifer/distilbart-cnn-6-6"
25
+ try:
26
+ # Load tokenizer and model for CPU
27
+ tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=False)
28
+ model = AutoModelForSeq2SeqLM.from_pretrained(
29
+ model_name,
30
+ torch_dtype=torch.float32, # Use float32 for CPU
31
+ use_safetensors=True, # Ensure safe loading
32
+ trust_remote_code=False
33
+ )
34
+
35
+ # Prepare prompt
36
+ prompt = f"""
37
+ You are an AI assistant analyzing project delay risks for a construction project.
38
+ Based on the following data, provide 2-4 concise insights or mitigation strategies as a list:
39
+ - Project: {input_data.get('project_name', 'Unnamed Project')}
40
+ - Phase: {input_data.get('phase', '')}
41
+ - Task: {input_data.get('task', '')}
42
+ - Expected Duration: {input_data.get('task_expected_duration', 0)} days
43
+ - Actual Duration: {input_data.get('task_actual_duration', 0)} days
44
+ - Current Progress: {input_data.get('current_progress', 0)}%
45
+ - Workforce Gap: {input_data.get('workforce_gap', 0)}%
46
+ - Workforce Skill Level: {input_data.get('workforce_skill_level', '').lower()}
47
+ - Shift Hours: {input_data.get('workforce_shift_hours', 0)} hours
48
+ - Weather Impact Score: {input_data.get('weather_impact_score', 0)} (Condition: {get_weather_condition(input_data.get('weather_impact_score', 0))})
49
+ - Calculated Delay Risk: {delay_risk:.1f}%
50
+
51
+ Format the response as a list of strings, e.g., ["Insight 1", "Insight 2"].
52
+ """
53
+
54
+ # Tokenize and generate with no_grad for memory efficiency
55
+ with torch.no_grad():
56
+ inputs = tokenizer(prompt, return_tensors="pt", max_length=512, truncation=True).to("cpu")
57
+ outputs = model.generate(
58
+ **inputs,
59
+ max_new_tokens=150, # Smaller output for CPU efficiency
60
+ num_beams=4, # Beam search for better quality
61
+ temperature=0.7,
62
+ do_sample=True
63
+ )
64
+ response = tokenizer.decode(outputs[0], skip_special_tokens=True)
65
+
66
+ # Parse response into a list
67
+ insights = [line.strip() for line in response.split("\n") if line.strip() and line.strip() not in [prompt]]
68
+ return insights[:4] # Limit to 2-4 insights
69
+
70
+ except Exception as e:
71
+ print(f"Error with model inference: {e}")
72
+ return ["AI model unavailable; monitor progress and resource allocation."]
73
+
74
+ def predict_delay(input_data: Dict) -> Dict:
75
  """
76
  Predict delay probability based on project task data.
77
  Uses task duration, progress, workforce info, and weather impact.
78
+ Insights are generated by DistilBART (CPU).
79
  """
80
  phase = input_data.get("phase", "")
81
  task = input_data.get("task", "")
 
101
  }
102
 
103
  delay_risk = 0
 
104
 
105
  # 1. Duration overrun risk
106
  if expected_duration > 0 and actual_duration > expected_duration:
107
  overrun_pct = ((actual_duration - expected_duration) / expected_duration) * 100
108
  delay_risk += min(overrun_pct, 30)
 
109
 
110
  # 2. Progress lag risk
111
  if expected_duration > 0 and current_progress >= 0:
 
113
  if current_progress < expected_progress:
114
  progress_gap = expected_progress - current_progress
115
  delay_risk += min(progress_gap, 25)
 
116
 
117
  # 3. Workforce gap impact
118
  if workforce_gap_pct > 0:
119
  delay_risk += min(workforce_gap_pct * 0.5, 20)
 
120
 
121
  # 4. Skill level effect
122
  if skill_level == "low":
123
  delay_risk += 15
 
124
  elif skill_level == "medium":
125
  delay_risk += 7
126
 
127
  # 5. Shift hours effect
128
  if shift_hours < 8:
129
+ delay_risk += (8 - shift_hours) * 3
 
 
130
  elif shift_hours > 8:
131
+ delay_risk -= min((shift_hours - 8) * 2, 10)
 
 
 
 
132
 
133
  # 6. Weather impact effect
134
  if weather_score > 50:
135
  delay_risk += min(weather_score / 2, 20)
 
136
 
137
  # Ensure delay_risk is between 0 and 100
138
  delay_risk = max(0, min(delay_risk, 100))
 
142
  if phase in task_options:
143
  for t in task_options[phase]:
144
  task_risk = delay_risk
 
145
  if t != task:
146
  task_risk = min(max(task_risk + (hash(t) % 10 - 5), 0), 100) # ±5% variation
147
  high_risk_phases.append({
 
150
  "risk": round(task_risk, 1)
151
  })
152
 
153
+ # Generate AI-driven insights
154
+ insights = call_ai_model_for_insights(input_data, delay_risk)
 
 
 
 
 
 
 
 
 
 
 
 
 
155
 
156
  return {
157
  "project": input_data.get("project_name", "Unnamed Project"),