Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,170 +1,148 @@
|
|
| 1 |
-
import pandas as pd
|
| 2 |
-
import requests
|
| 3 |
-
import gradio as gr
|
| 4 |
import logging
|
| 5 |
-
|
|
|
|
| 6 |
from simple_salesforce import Salesforce
|
| 7 |
-
import datetime
|
| 8 |
|
| 9 |
# Configure logging
|
| 10 |
-
logging.basicConfig(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
logger = logging.getLogger(__name__)
|
| 12 |
|
| 13 |
-
# Salesforce credentials
|
| 14 |
SALESFORCE_USERNAME = "vaneshdevarapalli866@agentforce.com"
|
| 15 |
SALESFORCE_PASSWORD = "vanesh@331"
|
| 16 |
SALESFORCE_SECURITY_TOKEN = "VRUVbBOdG0s9Q4xy0W6DB1Y6b"
|
| 17 |
|
|
|
|
| 18 |
def connect_to_salesforce():
|
| 19 |
try:
|
| 20 |
-
|
| 21 |
username=SALESFORCE_USERNAME,
|
| 22 |
password=SALESFORCE_PASSWORD,
|
| 23 |
security_token=SALESFORCE_SECURITY_TOKEN,
|
| 24 |
-
domain="login"
|
| 25 |
)
|
| 26 |
logger.info("Connected to Salesforce successfully.")
|
| 27 |
-
return
|
| 28 |
except Exception as e:
|
| 29 |
-
logger.error(f"
|
| 30 |
raise
|
| 31 |
|
| 32 |
sf = connect_to_salesforce()
|
| 33 |
|
| 34 |
-
#
|
| 35 |
-
def
|
| 36 |
try:
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
logger.
|
|
|
|
|
|
|
|
|
|
| 43 |
return None
|
| 44 |
-
|
| 45 |
-
# Ensure numeric columns are properly typed
|
| 46 |
-
numeric_cols = [col for col in required_columns + optional_columns if col in df.columns and col not in ["Equipment_ID__c", "Equipment_Type__c"]]
|
| 47 |
-
for col in numeric_cols:
|
| 48 |
-
df[col] = pd.to_numeric(df[col], errors='coerce').fillna(0)
|
| 49 |
-
|
| 50 |
-
# Add missing optional columns with default value 0
|
| 51 |
-
for col in optional_columns:
|
| 52 |
-
if col not in df.columns:
|
| 53 |
-
df[col] = 0.0
|
| 54 |
-
|
| 55 |
-
return df
|
| 56 |
except Exception as e:
|
| 57 |
-
logger.error(f"
|
| 58 |
return None
|
| 59 |
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
for idx, row in filtered.iterrows():
|
| 82 |
-
s, conf = dummy_ai_suggestion(row)
|
| 83 |
-
filtered.at[idx, "AI_Suggestion__c"] = s
|
| 84 |
-
filtered.at[idx, "Suggestion_Confidence__c"] = conf
|
| 85 |
-
|
| 86 |
-
filtered = filtered[filtered["AI_Suggestion__c"].str.lower() == suggestion.lower()]
|
| 87 |
-
if filtered.empty:
|
| 88 |
-
return f"No equipment with suggestion '{suggestion}' for type '{equipment_type}'.", ""
|
| 89 |
-
|
| 90 |
-
cards = [
|
| 91 |
-
f"ID: {row['Equipment_ID__c']} | Usage: {row['Usage_Hours__c']:.2f} hrs | "
|
| 92 |
-
f"Idle: {row['Idle_Hours__c']:.2f} hrs | Move Freq: {row.get('Movement_Frequency__c', 0):.2f} | "
|
| 93 |
-
f"Cost/hr: ${row.get('Cost_Per_Hour__c', 0):.2f} | AI: {row['AI_Suggestion__c']} "
|
| 94 |
-
f"({row['Suggestion_Confidence__c']:.2%})"
|
| 95 |
-
for _, row in filtered.iterrows()
|
| 96 |
-
]
|
| 97 |
-
confidences = [f"{row['Equipment_ID__c']}: {row['Suggestion_Confidence__c']:.2%}"
|
| 98 |
-
for _, row in filtered.iterrows()]
|
| 99 |
-
return "\n\n".join(cards), "\n".join(confidences)
|
| 100 |
-
except Exception as e:
|
| 101 |
-
logger.error(f"Error in filter_equipment: {e}")
|
| 102 |
-
return "An error occurred while filtering equipment.", ""
|
| 103 |
|
| 104 |
-
# Save selected equipment record to Salesforce
|
| 105 |
-
def save_equipment_record(equipment_id, project_id, usage_hours, idle_hours,
|
| 106 |
-
ai_suggestion, suggestion_confidence, utilization_score,
|
| 107 |
-
report_link, last_maintenance):
|
| 108 |
try:
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
"
|
| 114 |
-
"
|
| 115 |
-
"
|
| 116 |
-
"
|
| 117 |
-
"AI_Suggestion__c": ai_suggestion,
|
| 118 |
-
"Suggestion_Confidence__c": float(suggestion_confidence),
|
| 119 |
-
"Utilization_Score__c": float(utilization_score),
|
| 120 |
-
"Report_Link__c": report_link,
|
| 121 |
-
"Last_Maintenance__c": last_maintenance_date,
|
| 122 |
-
"Dashboard_Flag__c": False
|
| 123 |
}
|
| 124 |
-
resp = sf.Equipment_Utilization_Record__c.create(record)
|
| 125 |
-
return f"Salesforce record created with ID: {resp['id']}"
|
| 126 |
except Exception as e:
|
| 127 |
-
logger.error(f"
|
| 128 |
-
return
|
| 129 |
-
|
| 130 |
-
# Gradio UI
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
usage_hours_in = gr.Number(label="Usage Hours")
|
| 148 |
-
idle_hours_in = gr.Number(label="Idle Hours")
|
| 149 |
-
ai_suggestion_in = gr.Textbox(label="AI Suggestion")
|
| 150 |
-
suggestion_confidence_in = gr.Number(label="Suggestion Confidence")
|
| 151 |
-
utilization_score_in = gr.Number(label="Utilization Score")
|
| 152 |
-
report_link_in = gr.Textbox(label="Report Link")
|
| 153 |
-
last_maintenance_in = gr.Textbox(label="Last Maintenance Date (YYYY-MM-DD)")
|
| 154 |
-
|
| 155 |
-
def update_display(equipment_type, suggestion_type):
|
| 156 |
-
return filter_equipment(equipment_type, suggestion_type)
|
| 157 |
|
| 158 |
-
etype.change(update_display, inputs=[etype, suggestion], outputs=[details, confidences])
|
| 159 |
-
suggestion.change(update_display, inputs=[etype, suggestion], outputs=[details, confidences])
|
| 160 |
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
|
| 169 |
if __name__ == "__main__":
|
| 170 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import logging
|
| 2 |
+
import sys
|
| 3 |
+
import gradio as gr
|
| 4 |
from simple_salesforce import Salesforce
|
|
|
|
| 5 |
|
| 6 |
# Configure logging
|
| 7 |
+
logging.basicConfig(
|
| 8 |
+
level=logging.INFO,
|
| 9 |
+
format="%(asctime)s - %(levelname)s - %(message)s",
|
| 10 |
+
handlers=[logging.StreamHandler(sys.stdout)],
|
| 11 |
+
)
|
| 12 |
logger = logging.getLogger(__name__)
|
| 13 |
|
| 14 |
+
# Your Salesforce credentials
|
| 15 |
SALESFORCE_USERNAME = "vaneshdevarapalli866@agentforce.com"
|
| 16 |
SALESFORCE_PASSWORD = "vanesh@331"
|
| 17 |
SALESFORCE_SECURITY_TOKEN = "VRUVbBOdG0s9Q4xy0W6DB1Y6b"
|
| 18 |
|
| 19 |
+
# Connect to Salesforce
|
| 20 |
def connect_to_salesforce():
|
| 21 |
try:
|
| 22 |
+
sf = Salesforce(
|
| 23 |
username=SALESFORCE_USERNAME,
|
| 24 |
password=SALESFORCE_PASSWORD,
|
| 25 |
security_token=SALESFORCE_SECURITY_TOKEN,
|
| 26 |
+
domain="login",
|
| 27 |
)
|
| 28 |
logger.info("Connected to Salesforce successfully.")
|
| 29 |
+
return sf
|
| 30 |
except Exception as e:
|
| 31 |
+
logger.error(f"Failed to connect to Salesforce: {e}")
|
| 32 |
raise
|
| 33 |
|
| 34 |
sf = connect_to_salesforce()
|
| 35 |
|
| 36 |
+
# Lookup Salesforce record ID by object API name and record Name (string)
|
| 37 |
+
def lookup_record_id(object_api_name, record_name):
|
| 38 |
try:
|
| 39 |
+
query = f"SELECT Id FROM {object_api_name} WHERE Name = '{record_name}' LIMIT 1"
|
| 40 |
+
result = sf.query(query)
|
| 41 |
+
records = result.get("records", [])
|
| 42 |
+
if records:
|
| 43 |
+
record_id = records[0]["Id"]
|
| 44 |
+
logger.info(f"Found {object_api_name} ID for '{record_name}': {record_id}")
|
| 45 |
+
return record_id
|
| 46 |
+
else:
|
| 47 |
+
logger.warning(f"No {object_api_name} record found with Name '{record_name}'")
|
| 48 |
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
except Exception as e:
|
| 50 |
+
logger.error(f"Error looking up {object_api_name} ID: {e}")
|
| 51 |
return None
|
| 52 |
|
| 53 |
+
# Dummy AI model (replace with your real AI logic or API call)
|
| 54 |
+
def dummy_ai_model(usage_hours, idle_hours):
|
| 55 |
+
if usage_hours > 5:
|
| 56 |
+
suggestion = "Move"
|
| 57 |
+
confidence = 90.0
|
| 58 |
+
utilization_score = 85.0
|
| 59 |
+
else:
|
| 60 |
+
suggestion = "Pause Rent"
|
| 61 |
+
confidence = 75.0
|
| 62 |
+
utilization_score = 60.0
|
| 63 |
+
return suggestion, confidence, utilization_score
|
| 64 |
+
|
| 65 |
+
def process_equipment_utilization(
|
| 66 |
+
equipment_name,
|
| 67 |
+
project_name,
|
| 68 |
+
usage_hours,
|
| 69 |
+
idle_hours,
|
| 70 |
+
report_link,
|
| 71 |
+
last_maintenance_date,
|
| 72 |
+
):
|
| 73 |
+
equipment_id = lookup_record_id("Equipment__c", equipment_name)
|
| 74 |
+
project_id = lookup_record_id("Project__c", project_name)
|
| 75 |
+
|
| 76 |
+
if not equipment_id or not project_id:
|
| 77 |
+
return {
|
| 78 |
+
"status": "Error",
|
| 79 |
+
"message": "Could not find Salesforce record IDs for Equipment or Project. Please check names.",
|
| 80 |
+
}
|
| 81 |
|
| 82 |
+
ai_suggestion, suggestion_confidence, utilization_score = dummy_ai_model(
|
| 83 |
+
usage_hours, idle_hours
|
| 84 |
+
)
|
| 85 |
|
| 86 |
+
record = {
|
| 87 |
+
"Equipment_ID__c": equipment_id,
|
| 88 |
+
"Project_ID__c": project_id,
|
| 89 |
+
"Usage_Hours__c": usage_hours,
|
| 90 |
+
"Idle_Hours__c": idle_hours,
|
| 91 |
+
"AI_Suggestion__c": ai_suggestion,
|
| 92 |
+
"Suggestion_Confidence__c": suggestion_confidence,
|
| 93 |
+
"Utilization_Score__c": utilization_score,
|
| 94 |
+
"Report_Link__c": report_link,
|
| 95 |
+
"Last_Maintenance__c": last_maintenance_date,
|
| 96 |
+
"Dashboard_Flag__c": False,
|
| 97 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
try:
|
| 100 |
+
response = sf.Equipment_Utilization_Record__c.create(record)
|
| 101 |
+
logger.info(f"Created Salesforce record: {response}")
|
| 102 |
+
return {
|
| 103 |
+
"status": "Success",
|
| 104 |
+
"Salesforce_Record_ID": response.get("id"),
|
| 105 |
+
"AI_Suggestion": ai_suggestion,
|
| 106 |
+
"Suggestion_Confidence": suggestion_confidence,
|
| 107 |
+
"Utilization_Score": utilization_score,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
}
|
|
|
|
|
|
|
| 109 |
except Exception as e:
|
| 110 |
+
logger.error(f"Failed to create Salesforce record: {e}")
|
| 111 |
+
return {"status": "Error", "message": str(e)}
|
| 112 |
+
|
| 113 |
+
# Gradio UI function
|
| 114 |
+
def gradio_submit(
|
| 115 |
+
equipment_name,
|
| 116 |
+
project_name,
|
| 117 |
+
usage_hours,
|
| 118 |
+
idle_hours,
|
| 119 |
+
report_link,
|
| 120 |
+
last_maintenance_date,
|
| 121 |
+
):
|
| 122 |
+
return process_equipment_utilization(
|
| 123 |
+
equipment_name,
|
| 124 |
+
project_name,
|
| 125 |
+
usage_hours,
|
| 126 |
+
idle_hours,
|
| 127 |
+
report_link,
|
| 128 |
+
last_maintenance_date,
|
| 129 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
|
|
|
|
|
|
|
| 131 |
|
| 132 |
+
iface = gr.Interface(
|
| 133 |
+
fn=gradio_submit,
|
| 134 |
+
inputs=[
|
| 135 |
+
gr.Textbox(label="Equipment Name (Salesforce Name field)"),
|
| 136 |
+
gr.Textbox(label="Project Name (Salesforce Name field)"),
|
| 137 |
+
gr.Number(label="Usage Hours", value=0, minimum=0),
|
| 138 |
+
gr.Number(label="Idle Hours", value=0, minimum=0),
|
| 139 |
+
gr.Textbox(label="Report Link (URL)", value=""),
|
| 140 |
+
gr.Textbox(label="Last Maintenance Date (YYYY-MM-DD)", value=""),
|
| 141 |
+
],
|
| 142 |
+
outputs=gr.JSON(label="Salesforce Insert Result"),
|
| 143 |
+
title="Equipment Utilization Record Creator with Name Lookup",
|
| 144 |
+
description="Input Equipment and Project names; the app looks up Salesforce IDs and creates the record.",
|
| 145 |
+
)
|
| 146 |
|
| 147 |
if __name__ == "__main__":
|
| 148 |
+
iface.launch(share=False)
|