AjaykumarPilla commited on
Commit
a1d1526
·
verified ·
1 Parent(s): 1083f05

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +46 -68
app.py CHANGED
@@ -4,7 +4,6 @@ from fastapi import FastAPI, Request
4
  from fastapi.responses import JSONResponse
5
  import uvicorn
6
  from sklearn.linear_model import LinearRegression
7
- from sklearn.model_selection import train_test_split
8
  import base64
9
  import os
10
  from datetime import datetime
@@ -18,9 +17,12 @@ import matplotlib.pyplot as plt
18
  import seaborn as sns
19
  import numpy as np
20
 
 
 
 
21
  weather_map = {"Cloudy": 0, "Rainy": 1, "Sunny": 2}
22
 
23
- # Load and preprocess training data
24
  print("Loading and preprocessing data...")
25
  try:
26
  if not os.path.exists("new_delay_data.csv"):
@@ -56,7 +58,7 @@ except Exception as e:
56
  print(f"Error preparing features: {e}")
57
  raise
58
 
59
- # Train model
60
  print("Training model...")
61
  try:
62
  model = LinearRegression()
@@ -66,7 +68,35 @@ except Exception as e:
66
  print(f"Error training model: {e}")
67
  raise
68
 
69
- # Function to generate heatmap and return path
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
  def generate_heatmap(phase, weather, model):
71
  print("Generating heatmap...")
72
  try:
@@ -101,16 +131,14 @@ def generate_heatmap(phase, weather, model):
101
  print(f"Heatmap generation failed: {e}")
102
  return None
103
 
104
- # Function to generate simple PDF with heatmap and return base64-encoded string
105
  def generate_pdf_report(phase, weather, absentee_pct, delay_log, prediction, risk, insight):
106
  print("Generating PDF report...")
107
  try:
108
  buffer = BytesIO()
109
  c = canvas.Canvas(buffer, pagesize=letter)
110
 
111
- # Register DejaVuSans font to support Unicode emojis
112
  try:
113
- # Assuming DejaVuSans.ttf is available in the project directory
114
  pdfmetrics.registerFont(TTFont('DejaVuSans', 'DejaVuSans.ttf'))
115
  c.setFont("DejaVuSans", 12)
116
  flag_indicator = " 🚩" if prediction >= 75 else ""
@@ -123,7 +151,7 @@ def generate_pdf_report(phase, weather, absentee_pct, delay_log, prediction, ris
123
  c.drawString(100, 730, f"Generated on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
124
 
125
  y_position = 700
126
- max_width = 400 # max width in points for wrapping text
127
 
128
  details = [
129
  f"Phase: {phase}",
@@ -132,23 +160,20 @@ def generate_pdf_report(phase, weather, absentee_pct, delay_log, prediction, ris
132
  f"Previous Delay Log: {delay_log}",
133
  f"Predicted Delay: {prediction}%{flag_indicator}",
134
  f"Risk Level: {risk}",
135
- "AI Insight:"
136
  ]
137
 
138
- # Wrap and draw each line properly
139
  for line in details:
140
  lines = simpleSplit(line, 'DejaVuSans' if 'DejaVuSans' in pdfmetrics.getRegisteredFontNames() else 'Helvetica', 12, max_width)
141
  for wrapped_line in lines:
142
  c.drawString(100, y_position, wrapped_line)
143
  y_position -= 16
144
 
145
- # Wrap and draw insight (which may be long)
146
  insight_lines = simpleSplit(insight, 'DejaVuSans' if 'DejaVuSans' in pdfmetrics.getRegisteredFontNames() else 'Helvetica', 12, max_width)
147
  for wrapped_line in insight_lines:
148
  c.drawString(100, y_position, wrapped_line)
149
  y_position -= 16
150
 
151
- # Add heatmap
152
  heatmap_path = generate_heatmap(phase, weather, model)
153
  if heatmap_path and os.path.exists(heatmap_path):
154
  c.drawString(100, y_position - 20, "Delay Prediction Heatmap:")
@@ -175,7 +200,7 @@ def generate_pdf_report(phase, weather, absentee_pct, delay_log, prediction, ris
175
  print(f"PDF generation failed: {e}")
176
  return None, None, None
177
 
178
- # Main prediction function
179
  def predict_delay(phase, weather, absentee_pct, delay_log):
180
  print(f"Predicting delay for Phase: {phase}, Weather: {weather}, Absentee: {absentee_pct}, Delay Log: {delay_log}")
181
  try:
@@ -194,60 +219,14 @@ def predict_delay(phase, weather, absentee_pct, delay_log):
194
  prediction = model.predict(input_data)[0]
195
  prediction = round(prediction, 2)
196
 
197
- # Tailored AI Insights
198
  if prediction >= 75:
199
  risk = "High Risk"
200
- insight = f"High delay risk ({prediction}%) in {phase} phase under {weather} conditions. "
201
- if absentee_pct > 30:
202
- insight += f"High absenteeism ({absentee_pct}%) is a major factor. Hire temporary workers or offer overtime incentives. "
203
- else:
204
- insight += f"Absenteeism ({absentee_pct}%) is moderate; ensure key staff are present for critical {phase} tasks. "
205
- if delay_log > 5:
206
- insight += f"Significant past delays ({delay_log}) detected; conduct a root cause analysis to address bottlenecks. "
207
- else:
208
- insight += f"Past delays ({delay_log}) are manageable; review task dependencies to prevent escalation. "
209
- if weather == "Rainy":
210
- insight += "Rainy weather increases risk; use protective coverings or shift to indoor tasks."
211
- elif weather == "Cloudy":
212
- insight += "Cloudy weather may slow progress; monitor conditions and prepare for potential rain."
213
- else:
214
- insight += "Sunny weather is optimal; maximize outdoor work to reduce delays."
215
  elif prediction >= 50:
216
  risk = "Moderate Risk"
217
- insight = f"Moderate delay risk ({prediction}%) in {phase} phase under {weather} conditions. "
218
- if absentee_pct > 30:
219
- insight += f"High absenteeism ({absentee_pct}%) needs attention; consider cross-training staff to cover gaps. "
220
- elif absentee_pct < 10:
221
- insight += f"Low absenteeism ({absentee_pct}%) is good; maintain attendance with morale-boosting measures. "
222
- else:
223
- insight += f"Moderate absenteeism ({absentee_pct}%) suggests reviewing workforce allocation for {phase} tasks. "
224
- if delay_log > 5:
225
- insight += f"Past delays ({delay_log}) indicate inefficiencies; streamline workflows in {phase}. "
226
- else:
227
- insight += f"Past delays ({delay_log}) are low; ensure timely material delivery to maintain progress. "
228
- if weather == "Rainy":
229
- insight += "Rainy weather may disrupt work; schedule flexible tasks and secure equipment."
230
- elif weather == "Cloudy":
231
- insight += "Cloudy weather is manageable; keep weather monitoring active."
232
- else:
233
- insight += "Sunny weather supports progress; optimize daily schedules to leverage good conditions."
234
  else:
235
  risk = "Low Risk"
236
- insight = f"Low delay risk ({prediction}%) in {phase} phase under {weather} conditions. "
237
- if absentee_pct > 30:
238
- insight += f"Despite low risk, high absenteeism ({absentee_pct}%) could escalate; monitor attendance closely. "
239
- else:
240
- insight += f"Absenteeism ({absentee_pct}%) is under control; sustain with regular team check-ins. "
241
- if delay_log > 5:
242
- insight += f"Past delays ({delay_log}) are notable; maintain vigilance to prevent recurrence in {phase}. "
243
- else:
244
- insight += f"Minimal past delays ({delay_log}); continue efficient task management in {phase}. "
245
- if weather == "Rainy":
246
- insight += "Rainy weather could pose minor risks; have contingency plans ready."
247
- elif weather == "Cloudy":
248
- insight += "Cloudy weather is unlikely to cause issues; maintain standard operations."
249
- else:
250
- insight += "Sunny weather is ideal; capitalize on it to stay ahead of schedule."
251
 
252
  pdf_base64, pdf_path, heatmap_path = generate_pdf_report(phase, weather, absentee_pct, delay_log, prediction, risk, insight)
253
 
@@ -256,7 +235,7 @@ def predict_delay(phase, weather, absentee_pct, delay_log):
256
  print(f"Prediction error: {e}")
257
  return None, None, f"Error: {e}", None, None, None
258
 
259
- # FastAPI for Salesforce
260
  api_app = FastAPI()
261
 
262
  @api_app.post("/predict")
@@ -287,11 +266,11 @@ async def predict_from_salesforce(request: Request):
287
  print(f"API error: {e}")
288
  return JSONResponse(status_code=500, content={"status": "error", "message": str(e)})
289
 
290
- # Gradio UI for manual testing
291
  try:
292
  print("Setting up Gradio UI...")
293
  with gr.Blocks() as demo:
294
- gr.Markdown("## 🏗️ Delay Predictor")
295
  with gr.Row():
296
  phase_input = gr.Textbox(label="Phase (Framing/Foundation/Finishing)", value="Framing")
297
  weather_input = gr.Textbox(label="Weather (Sunny/Rainy/Cloudy)", value="Sunny")
@@ -309,7 +288,7 @@ try:
309
  flag = " 🚩" if prediction >= 75 else ""
310
  return (f"Predicted Delay: {prediction}%{flag}\n"
311
  f"Risk Level: {risk}\n"
312
- f"Insight: {insight}\n"
313
  f"PDF Report: {'Saved locally at ' + pdf_path if pdf_path else 'Failed to generate'}\n"
314
  f"Heatmap: {'Saved locally at ' + heatmap_path if heatmap_path else 'Failed to generate'}\n"
315
  f"PDF Base64: {'Generated' if pdf_base64 else 'Not generated'}")
@@ -324,7 +303,7 @@ except Exception as e:
324
  print(f"Error setting up Gradio UI: {e}")
325
  raise
326
 
327
- # Mount Gradio inside FastAPI
328
  try:
329
  print("Mounting Gradio app...")
330
  app = gr.mount_gradio_app(api_app, demo, path="/")
@@ -333,11 +312,10 @@ except Exception as e:
333
  print(f"Error mounting Gradio app: {e}")
334
  raise
335
 
336
- # Run locally
337
  if __name__ == "__main__":
338
  print("Starting server on http://0.0.0.0:7860...")
339
  try:
340
  uvicorn.run(app, host="0.0.0.0", port=7860)
341
  except Exception as e:
342
  print(f"Server failed to start: {e}")
343
- raise
 
4
  from fastapi.responses import JSONResponse
5
  import uvicorn
6
  from sklearn.linear_model import LinearRegression
 
7
  import base64
8
  import os
9
  from datetime import datetime
 
17
  import seaborn as sns
18
  import numpy as np
19
 
20
+ # Import Hugging Face transformers pipeline for text generation
21
+ from transformers import pipeline
22
+
23
  weather_map = {"Cloudy": 0, "Rainy": 1, "Sunny": 2}
24
 
25
+ # Load and preprocess data
26
  print("Loading and preprocessing data...")
27
  try:
28
  if not os.path.exists("new_delay_data.csv"):
 
58
  print(f"Error preparing features: {e}")
59
  raise
60
 
61
+ # Train Linear Regression model
62
  print("Training model...")
63
  try:
64
  model = LinearRegression()
 
68
  print(f"Error training model: {e}")
69
  raise
70
 
71
+ # Load GPT-2 text generation pipeline for AI insights and migration plans
72
+ print("Loading AI text generation model...")
73
+ try:
74
+ text_generator = pipeline("text-generation", model="gpt2")
75
+ print("Text generation model loaded successfully.")
76
+ except Exception as e:
77
+ print(f"Failed to load text generation model: {e}")
78
+ raise
79
+
80
+ # Generate AI insight and migration plan dynamically
81
+ def generate_ai_insight(phase, weather, absentee_pct, delay_log, prediction):
82
+ prompt = (
83
+ f"Project phase: {phase}. Weather: {weather}. "
84
+ f"Absentee percentage: {absentee_pct}%. Previous delay log: {delay_log}. "
85
+ f"Predicted delay: {prediction}%. "
86
+ "Provide a concise AI-generated insight about delay risks and a practical migration plan "
87
+ "to reduce these delays and improve project efficiency."
88
+ )
89
+ try:
90
+ result = text_generator(prompt, max_length=150, num_return_sequences=1)
91
+ generated_text = result[0]['generated_text']
92
+ # Strip out prompt to get only generated part
93
+ insight = generated_text[len(prompt):].strip()
94
+ return insight
95
+ except Exception as e:
96
+ print(f"AI insight generation failed: {e}")
97
+ return "AI insight generation failed. Please check logs."
98
+
99
+ # Heatmap generation function (unchanged)
100
  def generate_heatmap(phase, weather, model):
101
  print("Generating heatmap...")
102
  try:
 
131
  print(f"Heatmap generation failed: {e}")
132
  return None
133
 
134
+ # PDF generation function (unchanged except uses AI-generated insight)
135
  def generate_pdf_report(phase, weather, absentee_pct, delay_log, prediction, risk, insight):
136
  print("Generating PDF report...")
137
  try:
138
  buffer = BytesIO()
139
  c = canvas.Canvas(buffer, pagesize=letter)
140
 
 
141
  try:
 
142
  pdfmetrics.registerFont(TTFont('DejaVuSans', 'DejaVuSans.ttf'))
143
  c.setFont("DejaVuSans", 12)
144
  flag_indicator = " 🚩" if prediction >= 75 else ""
 
151
  c.drawString(100, 730, f"Generated on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
152
 
153
  y_position = 700
154
+ max_width = 400
155
 
156
  details = [
157
  f"Phase: {phase}",
 
160
  f"Previous Delay Log: {delay_log}",
161
  f"Predicted Delay: {prediction}%{flag_indicator}",
162
  f"Risk Level: {risk}",
163
+ "AI Insight & Migration Plan:"
164
  ]
165
 
 
166
  for line in details:
167
  lines = simpleSplit(line, 'DejaVuSans' if 'DejaVuSans' in pdfmetrics.getRegisteredFontNames() else 'Helvetica', 12, max_width)
168
  for wrapped_line in lines:
169
  c.drawString(100, y_position, wrapped_line)
170
  y_position -= 16
171
 
 
172
  insight_lines = simpleSplit(insight, 'DejaVuSans' if 'DejaVuSans' in pdfmetrics.getRegisteredFontNames() else 'Helvetica', 12, max_width)
173
  for wrapped_line in insight_lines:
174
  c.drawString(100, y_position, wrapped_line)
175
  y_position -= 16
176
 
 
177
  heatmap_path = generate_heatmap(phase, weather, model)
178
  if heatmap_path and os.path.exists(heatmap_path):
179
  c.drawString(100, y_position - 20, "Delay Prediction Heatmap:")
 
200
  print(f"PDF generation failed: {e}")
201
  return None, None, None
202
 
203
+ # Main prediction logic
204
  def predict_delay(phase, weather, absentee_pct, delay_log):
205
  print(f"Predicting delay for Phase: {phase}, Weather: {weather}, Absentee: {absentee_pct}, Delay Log: {delay_log}")
206
  try:
 
219
  prediction = model.predict(input_data)[0]
220
  prediction = round(prediction, 2)
221
 
 
222
  if prediction >= 75:
223
  risk = "High Risk"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
224
  elif prediction >= 50:
225
  risk = "Moderate Risk"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
226
  else:
227
  risk = "Low Risk"
228
+
229
+ insight = generate_ai_insight(phase, weather, absentee_pct, delay_log, prediction)
 
 
 
 
 
 
 
 
 
 
 
 
 
230
 
231
  pdf_base64, pdf_path, heatmap_path = generate_pdf_report(phase, weather, absentee_pct, delay_log, prediction, risk, insight)
232
 
 
235
  print(f"Prediction error: {e}")
236
  return None, None, f"Error: {e}", None, None, None
237
 
238
+ # FastAPI app
239
  api_app = FastAPI()
240
 
241
  @api_app.post("/predict")
 
266
  print(f"API error: {e}")
267
  return JSONResponse(status_code=500, content={"status": "error", "message": str(e)})
268
 
269
+ # Gradio UI
270
  try:
271
  print("Setting up Gradio UI...")
272
  with gr.Blocks() as demo:
273
+ gr.Markdown("## 🏗️ Delay Predictor with AI Insights")
274
  with gr.Row():
275
  phase_input = gr.Textbox(label="Phase (Framing/Foundation/Finishing)", value="Framing")
276
  weather_input = gr.Textbox(label="Weather (Sunny/Rainy/Cloudy)", value="Sunny")
 
288
  flag = " 🚩" if prediction >= 75 else ""
289
  return (f"Predicted Delay: {prediction}%{flag}\n"
290
  f"Risk Level: {risk}\n"
291
+ f"Insight & Migration Plan:\n{insight}\n\n"
292
  f"PDF Report: {'Saved locally at ' + pdf_path if pdf_path else 'Failed to generate'}\n"
293
  f"Heatmap: {'Saved locally at ' + heatmap_path if heatmap_path else 'Failed to generate'}\n"
294
  f"PDF Base64: {'Generated' if pdf_base64 else 'Not generated'}")
 
303
  print(f"Error setting up Gradio UI: {e}")
304
  raise
305
 
306
+ # Mount Gradio app inside FastAPI
307
  try:
308
  print("Mounting Gradio app...")
309
  app = gr.mount_gradio_app(api_app, demo, path="/")
 
312
  print(f"Error mounting Gradio app: {e}")
313
  raise
314
 
 
315
  if __name__ == "__main__":
316
  print("Starting server on http://0.0.0.0:7860...")
317
  try:
318
  uvicorn.run(app, host="0.0.0.0", port=7860)
319
  except Exception as e:
320
  print(f"Server failed to start: {e}")
321
+ raise