Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -4,6 +4,8 @@ import logging
|
|
| 4 |
import matplotlib.pyplot as plt
|
| 5 |
import io
|
| 6 |
import base64
|
|
|
|
|
|
|
| 7 |
from simple_salesforce import Salesforce
|
| 8 |
from dotenv import load_dotenv
|
| 9 |
import requests
|
|
@@ -58,11 +60,29 @@ def generate_plot(planned_cost, actual_spend, forecast_cost):
|
|
| 58 |
buf_gradio = io.BytesIO()
|
| 59 |
plt.savefig(buf_gradio, format='png', bbox_inches='tight')
|
| 60 |
buf_gradio.seek(0)
|
| 61 |
-
|
|
|
|
| 62 |
|
| 63 |
plt.close()
|
| 64 |
return image_base64, gradio_image
|
| 65 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
# Prediction function with input validation and formatted output
|
| 67 |
def predict_risk(planned_cost, actual_spend, category, cement_index, labor_index, project_phase):
|
| 68 |
# Validate numeric inputs
|
|
@@ -73,7 +93,7 @@ def predict_risk(planned_cost, actual_spend, category, cement_index, labor_index
|
|
| 73 |
labor_index = float(labor_index) if labor_index else 0
|
| 74 |
except ValueError:
|
| 75 |
logger.error("Invalid input: Inputs must be numeric.")
|
| 76 |
-
return "Error: All numeric inputs (planned cost, actual spend, cement index, labor index) must be valid numbers.", None
|
| 77 |
|
| 78 |
logger.debug(f"Starting prediction with inputs: planned_cost={planned_cost}, actual_spend={actual_spend}, "
|
| 79 |
f"category={category}, cement_index={cement_index}, labor_index={labor_index}, project_phase={project_phase}")
|
|
@@ -136,7 +156,7 @@ def predict_risk(planned_cost, actual_spend, category, cement_index, labor_index
|
|
| 136 |
|
| 137 |
except Exception as e:
|
| 138 |
logger.error(f"Failed to save to Salesforce: {str(e)}")
|
| 139 |
-
return f"Error: Failed to save to Salesforce: {str(e)}", None
|
| 140 |
|
| 141 |
# Fetch exchange rates
|
| 142 |
try:
|
|
@@ -148,6 +168,9 @@ def predict_risk(planned_cost, actual_spend, category, cement_index, labor_index
|
|
| 148 |
logger.error(f"Failed to fetch exchange rates: {str(e)}")
|
| 149 |
forecast_cost_eur = "N/A"
|
| 150 |
|
|
|
|
|
|
|
|
|
|
| 151 |
# Format the output for Gradio
|
| 152 |
risk_level = "High" if total_risk == 1 else "Low"
|
| 153 |
output_text = (
|
|
@@ -164,24 +187,27 @@ def predict_risk(planned_cost, actual_spend, category, cement_index, labor_index
|
|
| 164 |
f"Total Risk: {total_risk}\n"
|
| 165 |
f"Forecasted Cost: ${forecast_cost:,.2f} (EUR: {forecast_cost_eur if isinstance(forecast_cost_eur, str) else f'{forecast_cost_eur:,.2f}'})\n"
|
| 166 |
f"Top Causes: {top_causes}\n"
|
| 167 |
-
f"PDF Report: {pdf_url}"
|
|
|
|
| 168 |
)
|
| 169 |
-
return output_text, chart_image
|
| 170 |
|
| 171 |
# Gradio interface
|
| 172 |
interface = gr.Interface(
|
| 173 |
fn=predict_risk,
|
| 174 |
inputs=[
|
| 175 |
gr.Textbox(label="Planned Cost", placeholder="Enter planned cost (e.g., 1200000)"),
|
| 176 |
-
gr.Textbox(label="Actual Spend", placeholder="Enter actual spend (e.g.,
|
| 177 |
gr.Dropdown(label="Category", choices=["Civil", "Electrical", "Plumbing", "Finishing", "Others"], value="Plumbing"),
|
| 178 |
-
gr.Textbox(label="Cement Index", placeholder="Enter cement index (e.g.,
|
| 179 |
-
gr.Textbox(label="Labor Index", placeholder="Enter labor index (e.g.,
|
| 180 |
gr.Dropdown(label="Project Phase", choices=["Planning", "Execution", "Closure"], value="Planning")
|
| 181 |
],
|
| 182 |
outputs=[
|
| 183 |
gr.Textbox(label="Prediction Results"),
|
| 184 |
-
gr.Image(label="Forecast Chart")
|
|
|
|
|
|
|
| 185 |
],
|
| 186 |
title="Budget Overrun Risk Estimator",
|
| 187 |
description="Enter project details to estimate budget overrun risk. All numeric fields are required."
|
|
|
|
| 4 |
import matplotlib.pyplot as plt
|
| 5 |
import io
|
| 6 |
import base64
|
| 7 |
+
from PIL import Image
|
| 8 |
+
import pandas as pd
|
| 9 |
from simple_salesforce import Salesforce
|
| 10 |
from dotenv import load_dotenv
|
| 11 |
import requests
|
|
|
|
| 60 |
buf_gradio = io.BytesIO()
|
| 61 |
plt.savefig(buf_gradio, format='png', bbox_inches='tight')
|
| 62 |
buf_gradio.seek(0)
|
| 63 |
+
# Convert BytesIO to PIL Image for Gradio
|
| 64 |
+
gradio_image = Image.open(buf_gradio)
|
| 65 |
|
| 66 |
plt.close()
|
| 67 |
return image_base64, gradio_image
|
| 68 |
|
| 69 |
+
# Function to generate an Excel file with prediction results
|
| 70 |
+
def generate_excel(planned_cost, actual_spend, forecast_cost, total_risk, insights, status, top_causes, forecast_cost_eur):
|
| 71 |
+
data = {
|
| 72 |
+
"Planned Cost ($)": [planned_cost],
|
| 73 |
+
"Actual Spend ($)": [actual_spend],
|
| 74 |
+
"Forecasted Cost ($)": [forecast_cost],
|
| 75 |
+
"Forecasted Cost (EUR)": [forecast_cost_eur if isinstance(forecast_cost_eur, str) else forecast_cost_eur],
|
| 76 |
+
"Total Risk": [total_risk],
|
| 77 |
+
"Insights": [insights],
|
| 78 |
+
"Status": [status],
|
| 79 |
+
"Top Causes": [top_causes]
|
| 80 |
+
}
|
| 81 |
+
df = pd.DataFrame(data)
|
| 82 |
+
excel_path = f"prediction_results_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx"
|
| 83 |
+
df.to_excel(excel_path, index=False)
|
| 84 |
+
return excel_path
|
| 85 |
+
|
| 86 |
# Prediction function with input validation and formatted output
|
| 87 |
def predict_risk(planned_cost, actual_spend, category, cement_index, labor_index, project_phase):
|
| 88 |
# Validate numeric inputs
|
|
|
|
| 93 |
labor_index = float(labor_index) if labor_index else 0
|
| 94 |
except ValueError:
|
| 95 |
logger.error("Invalid input: Inputs must be numeric.")
|
| 96 |
+
return "Error: All numeric inputs (planned cost, actual spend, cement index, labor index) must be valid numbers.", None, None, None
|
| 97 |
|
| 98 |
logger.debug(f"Starting prediction with inputs: planned_cost={planned_cost}, actual_spend={actual_spend}, "
|
| 99 |
f"category={category}, cement_index={cement_index}, labor_index={labor_index}, project_phase={project_phase}")
|
|
|
|
| 156 |
|
| 157 |
except Exception as e:
|
| 158 |
logger.error(f"Failed to save to Salesforce: {str(e)}")
|
| 159 |
+
return f"Error: Failed to save to Salesforce: {str(e)}", None, None, None
|
| 160 |
|
| 161 |
# Fetch exchange rates
|
| 162 |
try:
|
|
|
|
| 168 |
logger.error(f"Failed to fetch exchange rates: {str(e)}")
|
| 169 |
forecast_cost_eur = "N/A"
|
| 170 |
|
| 171 |
+
# Generate Excel file
|
| 172 |
+
excel_file = generate_excel(planned_cost, actual_spend, forecast_cost, total_risk, insights, status, top_causes, forecast_cost_eur)
|
| 173 |
+
|
| 174 |
# Format the output for Gradio
|
| 175 |
risk_level = "High" if total_risk == 1 else "Low"
|
| 176 |
output_text = (
|
|
|
|
| 187 |
f"Total Risk: {total_risk}\n"
|
| 188 |
f"Forecasted Cost: ${forecast_cost:,.2f} (EUR: {forecast_cost_eur if isinstance(forecast_cost_eur, str) else f'{forecast_cost_eur:,.2f}'})\n"
|
| 189 |
f"Top Causes: {top_causes}\n"
|
| 190 |
+
f"PDF Report: {pdf_url}\n"
|
| 191 |
+
f"Excel Report: [Download link below]"
|
| 192 |
)
|
| 193 |
+
return output_text, chart_image, pdf_url, excel_file
|
| 194 |
|
| 195 |
# Gradio interface
|
| 196 |
interface = gr.Interface(
|
| 197 |
fn=predict_risk,
|
| 198 |
inputs=[
|
| 199 |
gr.Textbox(label="Planned Cost", placeholder="Enter planned cost (e.g., 1200000)"),
|
| 200 |
+
gr.Textbox(label="Actual Spend", placeholder="Enter actual spend (e.g., 5000000)"),
|
| 201 |
gr.Dropdown(label="Category", choices=["Civil", "Electrical", "Plumbing", "Finishing", "Others"], value="Plumbing"),
|
| 202 |
+
gr.Textbox(label="Cement Index", placeholder="Enter cement index (e.g., 120)"),
|
| 203 |
+
gr.Textbox(label="Labor Index", placeholder="Enter labor index (e.g., 30)"),
|
| 204 |
gr.Dropdown(label="Project Phase", choices=["Planning", "Execution", "Closure"], value="Planning")
|
| 205 |
],
|
| 206 |
outputs=[
|
| 207 |
gr.Textbox(label="Prediction Results"),
|
| 208 |
+
gr.Image(label="Forecast Chart"),
|
| 209 |
+
gr.File(label="Download PDF Report"),
|
| 210 |
+
gr.File(label="Download Excel Report")
|
| 211 |
],
|
| 212 |
title="Budget Overrun Risk Estimator",
|
| 213 |
description="Enter project details to estimate budget overrun risk. All numeric fields are required."
|