Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -10,6 +10,9 @@ from simple_salesforce import Salesforce
|
|
| 10 |
from dotenv import load_dotenv
|
| 11 |
import requests
|
| 12 |
from datetime import datetime
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
# Set up logging
|
| 15 |
logging.basicConfig(level=logging.DEBUG)
|
|
@@ -45,26 +48,70 @@ def generate_plot(planned_cost, actual_spend, forecast_cost):
|
|
| 45 |
fig, ax = plt.subplots(figsize=(8, 6))
|
| 46 |
categories = ['Planned Cost', 'Actual Spend', 'Forecasted Cost']
|
| 47 |
values = [planned_cost, actual_spend, forecast_cost]
|
| 48 |
-
ax.bar(categories, values, color=['
|
| 49 |
-
ax.set_title("Budget Overview")
|
| 50 |
-
ax.set_ylabel("Amount ($)")
|
| 51 |
-
|
|
|
|
| 52 |
|
| 53 |
# Save plot to a bytes buffer for Salesforce
|
| 54 |
buf = io.BytesIO()
|
| 55 |
-
plt.savefig(buf, format='png', bbox_inches='tight')
|
| 56 |
buf.seek(0)
|
| 57 |
image_base64 = base64.b64encode(buf.read()).decode('utf-8')
|
| 58 |
|
| 59 |
-
# Save plot to another buffer for Gradio
|
| 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):
|
|
@@ -137,8 +184,8 @@ def predict_risk(planned_cost, actual_spend, category, cement_index, labor_index
|
|
| 137 |
logger.debug(f"Salesforce create result: {result}")
|
| 138 |
record_id = result['id']
|
| 139 |
|
| 140 |
-
# Generate the plot for
|
| 141 |
-
plot_data, chart_image = generate_plot(planned_cost, actual_spend, forecast_cost)
|
| 142 |
attachment = {
|
| 143 |
"ParentId": record_id,
|
| 144 |
"Name": f"Budget_Overview_{datetime.now().strftime('%Y%m%d_%H%M%S')}.png",
|
|
@@ -168,6 +215,9 @@ def predict_risk(planned_cost, actual_spend, category, cement_index, labor_index
|
|
| 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 |
|
|
@@ -187,10 +237,11 @@ def predict_risk(planned_cost, actual_spend, category, cement_index, labor_index
|
|
| 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
|
|
|
|
| 191 |
f"Excel Report: [Download link below]"
|
| 192 |
)
|
| 193 |
-
return output_text, chart_image,
|
| 194 |
|
| 195 |
# Gradio interface
|
| 196 |
interface = gr.Interface(
|
|
@@ -206,7 +257,7 @@ interface = gr.Interface(
|
|
| 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",
|
|
|
|
| 10 |
from dotenv import load_dotenv
|
| 11 |
import requests
|
| 12 |
from datetime import datetime
|
| 13 |
+
from reportlab.lib.pagesizes import letter
|
| 14 |
+
from reportlab.pdfgen import canvas
|
| 15 |
+
from reportlab.lib.utils import ImageReader
|
| 16 |
|
| 17 |
# Set up logging
|
| 18 |
logging.basicConfig(level=logging.DEBUG)
|
|
|
|
| 48 |
fig, ax = plt.subplots(figsize=(8, 6))
|
| 49 |
categories = ['Planned Cost', 'Actual Spend', 'Forecasted Cost']
|
| 50 |
values = [planned_cost, actual_spend, forecast_cost]
|
| 51 |
+
ax.bar(categories, values, color=['#1f77b4', '#ff7f0e', '#2ca02c']) # Improved colors
|
| 52 |
+
ax.set_title("Budget Overview", fontsize=14, pad=15)
|
| 53 |
+
ax.set_ylabel("Amount ($)", fontsize=12)
|
| 54 |
+
ax.tick_params(axis='x', rotation=45)
|
| 55 |
+
ax.grid(True, axis='y', linestyle='--', alpha=0.7)
|
| 56 |
|
| 57 |
# Save plot to a bytes buffer for Salesforce
|
| 58 |
buf = io.BytesIO()
|
| 59 |
+
plt.savefig(buf, format='png', bbox_inches='tight', dpi=100)
|
| 60 |
buf.seek(0)
|
| 61 |
image_base64 = base64.b64encode(buf.read()).decode('utf-8')
|
| 62 |
|
| 63 |
+
# Save plot to another buffer for Gradio and PDF
|
| 64 |
buf_gradio = io.BytesIO()
|
| 65 |
+
plt.savefig(buf_gradio, format='png', bbox_inches='tight', dpi=100)
|
| 66 |
buf_gradio.seek(0)
|
| 67 |
# Convert BytesIO to PIL Image for Gradio
|
| 68 |
gradio_image = Image.open(buf_gradio)
|
| 69 |
|
| 70 |
+
# Save plot to a temporary file for PDF generation
|
| 71 |
+
buf_pdf = io.BytesIO()
|
| 72 |
+
plt.savefig(buf_pdf, format='png', bbox_inches='tight', dpi=100)
|
| 73 |
+
buf_pdf.seek(0)
|
| 74 |
+
|
| 75 |
plt.close()
|
| 76 |
+
return image_base64, gradio_image, buf_pdf
|
| 77 |
+
|
| 78 |
+
# Function to generate a PDF report locally
|
| 79 |
+
def generate_pdf(planned_cost, actual_spend, forecast_cost, total_risk, insights, status, top_causes, forecast_cost_eur, chart_image):
|
| 80 |
+
pdf_path = f"budget_report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.pdf"
|
| 81 |
+
c = canvas.Canvas(pdf_path, pagesize=letter)
|
| 82 |
+
width, height = letter
|
| 83 |
+
|
| 84 |
+
# Title
|
| 85 |
+
c.setFont("Helvetica-Bold", 16)
|
| 86 |
+
c.drawString(50, height - 50, "Budget Overrun Risk Report")
|
| 87 |
+
|
| 88 |
+
# Prediction Metrics
|
| 89 |
+
c.setFont("Helvetica", 12)
|
| 90 |
+
y_position = height - 100
|
| 91 |
+
c.drawString(50, y_position, f"Planned Cost: ${planned_cost:,.2f}")
|
| 92 |
+
y_position -= 20
|
| 93 |
+
c.drawString(50, y_position, f"Actual Spend: ${actual_spend:,.2f}")
|
| 94 |
+
y_position -= 20
|
| 95 |
+
c.drawString(50, y_position, f"Forecasted Cost: ${forecast_cost:,.2f}")
|
| 96 |
+
y_position -= 20
|
| 97 |
+
c.drawString(50, y_position, f"Forecasted Cost (EUR): {forecast_cost_eur if isinstance(forecast_cost_eur, str) else f'{forecast_cost_eur:,.2f}'}")
|
| 98 |
+
y_position -= 20
|
| 99 |
+
c.drawString(50, y_position, f"Total Risk: {total_risk}")
|
| 100 |
+
y_position -= 20
|
| 101 |
+
c.drawString(50, y_position, f"Status: {status}")
|
| 102 |
+
y_position -= 20
|
| 103 |
+
c.drawString(50, y_position, f"Insights: {insights}")
|
| 104 |
+
y_position -= 20
|
| 105 |
+
c.drawString(50, y_position, f"Top Causes: {top_causes}")
|
| 106 |
+
y_position -= 40
|
| 107 |
+
|
| 108 |
+
# Add the chart
|
| 109 |
+
chart_reader = ImageReader(chart_image)
|
| 110 |
+
c.drawImage(chart_reader, 50, y_position - 300, width=500, height=300)
|
| 111 |
+
|
| 112 |
+
c.showPage()
|
| 113 |
+
c.save()
|
| 114 |
+
return pdf_path
|
| 115 |
|
| 116 |
# Function to generate an Excel file with prediction results
|
| 117 |
def generate_excel(planned_cost, actual_spend, forecast_cost, total_risk, insights, status, top_causes, forecast_cost_eur):
|
|
|
|
| 184 |
logger.debug(f"Salesforce create result: {result}")
|
| 185 |
record_id = result['id']
|
| 186 |
|
| 187 |
+
# Generate the plot for Salesforce, Gradio, and PDF
|
| 188 |
+
plot_data, chart_image, chart_image_pdf = generate_plot(planned_cost, actual_spend, forecast_cost)
|
| 189 |
attachment = {
|
| 190 |
"ParentId": record_id,
|
| 191 |
"Name": f"Budget_Overview_{datetime.now().strftime('%Y%m%d_%H%M%S')}.png",
|
|
|
|
| 215 |
logger.error(f"Failed to fetch exchange rates: {str(e)}")
|
| 216 |
forecast_cost_eur = "N/A"
|
| 217 |
|
| 218 |
+
# Generate local PDF report
|
| 219 |
+
pdf_file = generate_pdf(planned_cost, actual_spend, forecast_cost, total_risk, insights, status, top_causes, forecast_cost_eur, chart_image_pdf)
|
| 220 |
+
|
| 221 |
# Generate Excel file
|
| 222 |
excel_file = generate_excel(planned_cost, actual_spend, forecast_cost, total_risk, insights, status, top_causes, forecast_cost_eur)
|
| 223 |
|
|
|
|
| 237 |
f"Total Risk: {total_risk}\n"
|
| 238 |
f"Forecasted Cost: ${forecast_cost:,.2f} (EUR: {forecast_cost_eur if isinstance(forecast_cost_eur, str) else f'{forecast_cost_eur:,.2f}'})\n"
|
| 239 |
f"Top Causes: {top_causes}\n"
|
| 240 |
+
f"Salesforce PDF URL (requires login): {pdf_url}\n"
|
| 241 |
+
f"Local PDF Report: [Download link below]\n"
|
| 242 |
f"Excel Report: [Download link below]"
|
| 243 |
)
|
| 244 |
+
return output_text, chart_image, pdf_file, excel_file
|
| 245 |
|
| 246 |
# Gradio interface
|
| 247 |
interface = gr.Interface(
|
|
|
|
| 257 |
outputs=[
|
| 258 |
gr.Textbox(label="Prediction Results"),
|
| 259 |
gr.Image(label="Forecast Chart"),
|
| 260 |
+
gr.File(label="Download Local PDF Report"),
|
| 261 |
gr.File(label="Download Excel Report")
|
| 262 |
],
|
| 263 |
title="Budget Overrun Risk Estimator",
|