Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,107 +1,161 @@
|
|
| 1 |
import pandas as pd
|
| 2 |
-
import
|
| 3 |
import gradio as gr
|
|
|
|
|
|
|
| 4 |
from simple_salesforce import Salesforce
|
| 5 |
|
| 6 |
-
#
|
| 7 |
-
logging.basicConfig(level=logging.INFO)
|
| 8 |
-
logger = logging.getLogger(__name__)
|
| 9 |
-
|
| 10 |
-
# Salesforce credentials
|
| 11 |
SALESFORCE_USERNAME = "vaneshdevarapalli866@agentforce.com"
|
| 12 |
SALESFORCE_PASSWORD = "vanesh@331"
|
| 13 |
SALESFORCE_SECURITY_TOKEN = "VRUVbBOdG0s9Q4xy0W6DB1Y6b"
|
| 14 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
# Connect to Salesforce
|
| 16 |
def connect_to_salesforce():
|
| 17 |
try:
|
| 18 |
-
|
| 19 |
username=SALESFORCE_USERNAME,
|
| 20 |
password=SALESFORCE_PASSWORD,
|
| 21 |
security_token=SALESFORCE_SECURITY_TOKEN,
|
| 22 |
domain="login"
|
| 23 |
)
|
| 24 |
-
logger.info("Connected to Salesforce")
|
| 25 |
-
return
|
| 26 |
except Exception as e:
|
| 27 |
-
logger.error(f"Salesforce connection
|
| 28 |
raise
|
| 29 |
|
| 30 |
sf = connect_to_salesforce()
|
| 31 |
|
| 32 |
-
# Load
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
|
| 41 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
def filter_equipment(equipment_type, suggestion):
|
| 43 |
-
if not equipment_type or not suggestion:
|
| 44 |
-
return "", ""
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
|
| 68 |
-
# Export filtered
|
| 69 |
def export_csv(equipment_type, suggestion):
|
| 70 |
-
|
| 71 |
-
if filtered.empty:
|
| 72 |
return None
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
filtered
|
| 78 |
-
filtered
|
| 79 |
-
|
| 80 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
return None
|
| 82 |
-
csv_path = "filtered_equipment.csv"
|
| 83 |
-
filtered.to_csv(csv_path, index=False)
|
| 84 |
-
return csv_path
|
| 85 |
|
| 86 |
-
# Build Gradio UI
|
| 87 |
-
with gr.Blocks(
|
| 88 |
gr.Markdown("# Equipment Utilization Dashboard")
|
| 89 |
gr.Markdown("Filter equipment by type and AI suggestion to optimize utilization.")
|
| 90 |
|
| 91 |
with gr.Row():
|
| 92 |
-
etype = gr.Dropdown(choices=equipment_types, label="Equipment Type"
|
| 93 |
-
|
|
|
|
|
|
|
| 94 |
|
| 95 |
-
details = gr.Textbox(label="Equipment Details", lines=8)
|
| 96 |
-
confidence = gr.Textbox(label="Confidence Scores", lines=5)
|
| 97 |
|
| 98 |
-
export_btn = gr.Button("Export to CSV")
|
| 99 |
csv_file = gr.File(label="Download CSV")
|
| 100 |
|
| 101 |
-
#
|
| 102 |
etype.change(fn=filter_equipment, inputs=[etype, suggestion], outputs=[details, confidence])
|
| 103 |
suggestion.change(fn=filter_equipment, inputs=[etype, suggestion], outputs=[details, confidence])
|
| 104 |
export_btn.click(fn=export_csv, inputs=[etype, suggestion], outputs=csv_file)
|
| 105 |
|
| 106 |
if __name__ == "__main__":
|
| 107 |
-
app.launch()
|
|
|
|
| 1 |
import pandas as pd
|
| 2 |
+
import requests
|
| 3 |
import gradio as gr
|
| 4 |
+
import logging
|
| 5 |
+
from uuid import uuid4
|
| 6 |
from simple_salesforce import Salesforce
|
| 7 |
|
| 8 |
+
# Salesforce credentials - replace with yours securely
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
SALESFORCE_USERNAME = "vaneshdevarapalli866@agentforce.com"
|
| 10 |
SALESFORCE_PASSWORD = "vanesh@331"
|
| 11 |
SALESFORCE_SECURITY_TOKEN = "VRUVbBOdG0s9Q4xy0W6DB1Y6b"
|
| 12 |
|
| 13 |
+
# Configure logging
|
| 14 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 15 |
+
logger = logging.getLogger(__name__)
|
| 16 |
+
|
| 17 |
# Connect to Salesforce
|
| 18 |
def connect_to_salesforce():
|
| 19 |
try:
|
| 20 |
+
sf_instance = Salesforce(
|
| 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 sf_instance
|
| 28 |
except Exception as e:
|
| 29 |
+
logger.error(f"Salesforce connection failed: {e}")
|
| 30 |
raise
|
| 31 |
|
| 32 |
sf = connect_to_salesforce()
|
| 33 |
|
| 34 |
+
# Load dataset
|
| 35 |
+
def load_dataset(file_path="equipment_data.csv"):
|
| 36 |
+
try:
|
| 37 |
+
df = pd.read_csv(file_path)
|
| 38 |
+
required_columns = ["Equipment_ID__c", "Equipment_Type__c", "Usage_Hours__c", "Idle_Hours__c"]
|
| 39 |
+
optional_columns = ["Movement_Frequency__c", "Cost_Per_Hour__c"]
|
| 40 |
+
missing_required = [col for col in required_columns if col not in df.columns]
|
| 41 |
+
if missing_required:
|
| 42 |
+
logger.error(f"Missing required columns: {missing_required}")
|
| 43 |
+
return None
|
| 44 |
+
|
| 45 |
+
# Convert numeric columns properly
|
| 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')
|
| 49 |
+
|
| 50 |
+
# Fill NaNs with 0 for numeric columns
|
| 51 |
+
if df[numeric_cols].isnull().any().any():
|
| 52 |
+
logger.warning("NaN detected in numeric columns, filling with 0")
|
| 53 |
+
df[numeric_cols] = df[numeric_cols].fillna(0)
|
| 54 |
+
|
| 55 |
+
# Add missing optional columns
|
| 56 |
+
for col in optional_columns:
|
| 57 |
+
if col not in df.columns:
|
| 58 |
+
df[col] = 0.0
|
| 59 |
+
return df
|
| 60 |
+
except Exception as e:
|
| 61 |
+
logger.error(f"Failed to load dataset: {e}")
|
| 62 |
+
return None
|
| 63 |
|
| 64 |
+
df = load_dataset()
|
| 65 |
+
equipment_types = sorted(df["Equipment_Type__c"].dropna().unique().tolist()) if df is not None and not df.empty else ["No Equipment Types"]
|
| 66 |
+
suggestion_types = ["Move", "Pause Rent", "Repair", "Replace"]
|
| 67 |
|
| 68 |
+
# Dummy AI suggestion function (Replace with your actual AI integration)
|
| 69 |
+
def call_model(row):
|
| 70 |
+
# Example logic for AI suggestion (random or based on usage hours)
|
| 71 |
+
usage = float(row.get("Usage_Hours__c", 0))
|
| 72 |
+
if usage > 8:
|
| 73 |
+
return "Pause Rent", 0.9
|
| 74 |
+
elif usage > 4:
|
| 75 |
+
return "Move", 0.8
|
| 76 |
+
else:
|
| 77 |
+
return "Repair", 0.7
|
| 78 |
+
|
| 79 |
+
# Filter equipment by type and suggestion
|
| 80 |
def filter_equipment(equipment_type, suggestion):
|
| 81 |
+
if not equipment_type or not suggestion or df is None or df.empty:
|
| 82 |
+
return "No data available or invalid filters selected.", ""
|
| 83 |
+
try:
|
| 84 |
+
filtered = df[df["Equipment_Type__c"].str.lower() == equipment_type.lower()].copy()
|
| 85 |
+
if filtered.empty:
|
| 86 |
+
return f"No equipment found for type: {equipment_type}.", ""
|
| 87 |
+
|
| 88 |
+
# Apply dummy AI model predictions
|
| 89 |
+
filtered["AI_Suggestion__c"] = None
|
| 90 |
+
filtered["Suggestion_Confidence__c"] = 0.0
|
| 91 |
+
for idx, row in filtered.iterrows():
|
| 92 |
+
s, conf = call_model(row)
|
| 93 |
+
filtered.at[idx, "AI_Suggestion__c"] = s
|
| 94 |
+
filtered.at[idx, "Suggestion_Confidence__c"] = conf
|
| 95 |
+
|
| 96 |
+
# Filter by suggestion
|
| 97 |
+
filtered = filtered[filtered["AI_Suggestion__c"].str.lower() == suggestion.lower()]
|
| 98 |
+
if filtered.empty:
|
| 99 |
+
return f"No equipment with suggestion '{suggestion}' for type '{equipment_type}'.", ""
|
| 100 |
+
|
| 101 |
+
# Generate display text for equipment and confidence
|
| 102 |
+
cards = [
|
| 103 |
+
f"ID: {row['Equipment_ID__c']} | Usage: {row['Usage_Hours__c']:.2f} hrs | "
|
| 104 |
+
f"Idle: {row['Idle_Hours__c']:.2f} hrs | AI Suggestion: {row['AI_Suggestion__c']} "
|
| 105 |
+
f"({row['Suggestion_Confidence__c']:.2%})"
|
| 106 |
+
for _, row in filtered.iterrows()
|
| 107 |
+
]
|
| 108 |
+
confidences = [f"{row['Equipment_ID__c']}: {row['Suggestion_Confidence__c']:.2%}" for _, row in filtered.iterrows()]
|
| 109 |
+
return "\n\n".join(cards), "\n".join(confidences)
|
| 110 |
+
except Exception as e:
|
| 111 |
+
logger.error(f"Error filtering equipment: {e}")
|
| 112 |
+
return "An error occurred while filtering equipment.", ""
|
| 113 |
|
| 114 |
+
# Export filtered results to CSV file
|
| 115 |
def export_csv(equipment_type, suggestion):
|
| 116 |
+
if not equipment_type or not suggestion or df is None or df.empty:
|
|
|
|
| 117 |
return None
|
| 118 |
+
try:
|
| 119 |
+
filtered = df[df["Equipment_Type__c"].str.lower() == equipment_type.lower()].copy()
|
| 120 |
+
if filtered.empty:
|
| 121 |
+
return None
|
| 122 |
+
filtered["AI_Suggestion__c"] = None
|
| 123 |
+
filtered["Suggestion_Confidence__c"] = 0.0
|
| 124 |
+
for idx, row in filtered.iterrows():
|
| 125 |
+
s, conf = call_model(row)
|
| 126 |
+
filtered.at[idx, "AI_Suggestion__c"] = s
|
| 127 |
+
filtered.at[idx, "Suggestion_Confidence__c"] = conf
|
| 128 |
+
filtered = filtered[filtered["AI_Suggestion__c"].str.lower() == suggestion.lower()]
|
| 129 |
+
if filtered.empty:
|
| 130 |
+
return None
|
| 131 |
+
filename = f"filtered_equipment_{uuid4().hex[:8]}.csv"
|
| 132 |
+
filtered.to_csv(filename, index=False)
|
| 133 |
+
return filename
|
| 134 |
+
except Exception as e:
|
| 135 |
+
logger.error(f"Error exporting CSV: {e}")
|
| 136 |
return None
|
|
|
|
|
|
|
|
|
|
| 137 |
|
| 138 |
+
# Build Gradio UI without theme to avoid errors
|
| 139 |
+
with gr.Blocks() as app:
|
| 140 |
gr.Markdown("# Equipment Utilization Dashboard")
|
| 141 |
gr.Markdown("Filter equipment by type and AI suggestion to optimize utilization.")
|
| 142 |
|
| 143 |
with gr.Row():
|
| 144 |
+
etype = gr.Dropdown(choices=equipment_types, label="Equipment Type",
|
| 145 |
+
value=equipment_types[0] if equipment_types else None)
|
| 146 |
+
suggestion = gr.Dropdown(choices=suggestion_types, label="Suggestion Type",
|
| 147 |
+
value=suggestion_types[0])
|
| 148 |
|
| 149 |
+
details = gr.Textbox(label="Equipment Details", lines=8, placeholder="Select equipment type and suggestion...")
|
| 150 |
+
confidence = gr.Textbox(label="Confidence Scores", lines=5, placeholder="Confidence scores will appear here...")
|
| 151 |
|
| 152 |
+
export_btn = gr.Button("Export to CSV", variant="primary")
|
| 153 |
csv_file = gr.File(label="Download CSV")
|
| 154 |
|
| 155 |
+
# Define interactions
|
| 156 |
etype.change(fn=filter_equipment, inputs=[etype, suggestion], outputs=[details, confidence])
|
| 157 |
suggestion.change(fn=filter_equipment, inputs=[etype, suggestion], outputs=[details, confidence])
|
| 158 |
export_btn.click(fn=export_csv, inputs=[etype, suggestion], outputs=csv_file)
|
| 159 |
|
| 160 |
if __name__ == "__main__":
|
| 161 |
+
app.launch(share=False)
|