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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import gradio as gr
|
| 3 |
+
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
|
| 4 |
+
import os
|
| 5 |
+
from fastapi import FastAPI
|
| 6 |
+
from pydantic import BaseModel
|
| 7 |
+
from simple_salesforce import Salesforce
|
| 8 |
+
from dotenv import load_dotenv
|
| 9 |
+
|
| 10 |
+
# Load environment variables
|
| 11 |
+
load_dotenv()
|
| 12 |
+
|
| 13 |
+
# Salesforce connection
|
| 14 |
+
def get_salesforce_connection():
|
| 15 |
+
try:
|
| 16 |
+
# Load credentials from environment variables
|
| 17 |
+
username = os.getenv("SF_USERNAME")
|
| 18 |
+
password = os.getenv("SF_PASSWORD")
|
| 19 |
+
security_token = os.getenv("SF_SECURITY_TOKEN")
|
| 20 |
+
domain = os.getenv("SF_DOMAIN", "login") # Default to production (login.salesforce.com)
|
| 21 |
+
|
| 22 |
+
# Validate credentials
|
| 23 |
+
if not all([username, password, security_token, domain]):
|
| 24 |
+
missing = []
|
| 25 |
+
if not username:
|
| 26 |
+
missing.append("SF_USERNAME")
|
| 27 |
+
if not password:
|
| 28 |
+
missing.append("SF_PASSWORD")
|
| 29 |
+
if not security_token:
|
| 30 |
+
missing.append("SF_SECURITY_TOKEN")
|
| 31 |
+
if not domain:
|
| 32 |
+
missing.append("SF_DOMAIN")
|
| 33 |
+
raise ValueError(f"Missing environment variables: {', '.join(missing)}. Set them in .env or Space environment variables.")
|
| 34 |
+
|
| 35 |
+
# Ensure all are strings
|
| 36 |
+
if not all(isinstance(x, str) for x in [username, password, security_token, domain]):
|
| 37 |
+
raise ValueError("All Salesforce credentials (SF_USERNAME, SF_PASSWORD, SF_SECURITY_TOKEN, SF_DOMAIN) must be strings.")
|
| 38 |
+
|
| 39 |
+
sf = Salesforce(
|
| 40 |
+
username=username,
|
| 41 |
+
password=password,
|
| 42 |
+
security_token=security_token,
|
| 43 |
+
domain=domain
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
# Test connection by fetching user info
|
| 47 |
+
sf.User.get(sf.user_id)
|
| 48 |
+
return sf
|
| 49 |
+
except Exception as e:
|
| 50 |
+
raise Exception(f"Failed to connect to Salesforce: {str(e)}")
|
| 51 |
+
|
| 52 |
+
# Load Hugging Face token
|
| 53 |
+
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 54 |
+
|
| 55 |
+
# Model configuration
|
| 56 |
+
MODEL_PATH = "facebook/bart-large" # Public model
|
| 57 |
+
# MODEL_PATH = "your_actual_username/fine_tuned_bart_construction" # Uncomment after uploading
|
| 58 |
+
|
| 59 |
+
try:
|
| 60 |
+
model = AutoModelForSeq2SeqLM.from_pretrained(MODEL_PATH, use_auth_token=HF_TOKEN if HF_TOKEN else None)
|
| 61 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH, use_auth_token=HF_TOKEN if HF_TOKEN else None)
|
| 62 |
+
except Exception as e:
|
| 63 |
+
raise Exception(f"Failed to load model: {str(e)}")
|
| 64 |
+
|
| 65 |
+
# Define input model for FastAPI
|
| 66 |
+
class ChecklistInput(BaseModel):
|
| 67 |
+
role: str = "Supervisor"
|
| 68 |
+
project_id: str = "Unknown"
|
| 69 |
+
project_name: str = "Unknown Project"
|
| 70 |
+
milestones: str = "No milestones provided"
|
| 71 |
+
record_id: str = None
|
| 72 |
+
supervisor_id: str = None
|
| 73 |
+
project_id_sf: str = None
|
| 74 |
+
reflection_log: str = None
|
| 75 |
+
download_link: str = None
|
| 76 |
+
|
| 77 |
+
# Initialize FastAPI
|
| 78 |
+
app = FastAPI()
|
| 79 |
+
|
| 80 |
+
@app.post("/generate")
|
| 81 |
+
async def generate_checklist(data: ChecklistInput):
|
| 82 |
+
try:
|
| 83 |
+
inputs = f"Role: {data.role} Project: {data.project_id} ({data.project_name}) Milestones: {data.milestones}"
|
| 84 |
+
input_ids = tokenizer(inputs, return_tensors="pt", max_length=128, truncation=True).input_ids
|
| 85 |
+
outputs = model.generate(input_ids, max_length=128, num_beams=4, early_stopping=True)
|
| 86 |
+
checklist = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 87 |
+
tips = "1. Prioritize safety checks\n2. Review milestones\n3. Log progress"
|
| 88 |
+
kpi_flag = "delay" in data.milestones.lower() or "behind" in data.milestones.lower()
|
| 89 |
+
|
| 90 |
+
if data.record_id:
|
| 91 |
+
sf = get_salesforce_connection()
|
| 92 |
+
existing_record = sf.Supervisor_AI_Coaching__c.get(data.record_id, default={
|
| 93 |
+
'Name': '',
|
| 94 |
+
'Supervisor_ID__c': None,
|
| 95 |
+
'Project_ID__c': None,
|
| 96 |
+
'Reflection_Log__c': '',
|
| 97 |
+
'Download_Link__c': '',
|
| 98 |
+
'Engagement_Score__c': 0,
|
| 99 |
+
'KPI_Flag__c': False,
|
| 100 |
+
'Daily_Checklist__c': '',
|
| 101 |
+
'Suggested_Tips__c': ''
|
| 102 |
+
})
|
| 103 |
+
update_data = {
|
| 104 |
+
'Daily_Checklist__c': checklist,
|
| 105 |
+
'Suggested_Tips__c': tips,
|
| 106 |
+
'Engagement_Score__c': existing_record.get('Engagement_Score__c', 0) + 10,
|
| 107 |
+
'KPI_Flag__c': kpi_flag,
|
| 108 |
+
'Supervisor_ID__c': data.supervisor_id if data.supervisor_id else existing_record.get('Supervisor_ID__c'),
|
| 109 |
+
'Project_ID__c': data.project_id_sf if data.project_id_sf else existing_record.get('Project_ID__c'),
|
| 110 |
+
'Reflection_Log__c': data.reflection_log if data.reflection_log else existing_record.get('Reflection_Log__c', ''),
|
| 111 |
+
'Download_Link__c': data.download_link if data.download_link else existing_record.get('Download_Link__c', '')
|
| 112 |
+
}
|
| 113 |
+
sf.Supervisor_AI_Coaching__c.update(data.record_id, update_data)
|
| 114 |
+
|
| 115 |
+
return {
|
| 116 |
+
"checklist": checklist,
|
| 117 |
+
"tips": tips,
|
| 118 |
+
"kpi_flag": kpi_flag
|
| 119 |
+
}
|
| 120 |
+
except Exception as e:
|
| 121 |
+
return {"error": str(e)}
|
| 122 |
+
|
| 123 |
+
# Login and display records
|
| 124 |
+
def login_and_display(project_id_sf):
|
| 125 |
+
try:
|
| 126 |
+
sf = get_salesforce_connection()
|
| 127 |
+
query = f"SELECT Id, Name, Supervisor_ID__c, Project_ID__c, Daily_Checklist__c, Suggested_Tips__c, Reflection_Log__c, Engagement_Score__c, KPI_Flag__c, Download_Link__c FROM Supervisor_AI_Coaching__c WHERE Project_ID__c = '{project_id_sf}'"
|
| 128 |
+
records = sf.query(query)["records"]
|
| 129 |
+
if not records:
|
| 130 |
+
return "No records found for Project ID.", "", False
|
| 131 |
+
|
| 132 |
+
output = "Supervisor_AI_Coaching__c Records:\n"
|
| 133 |
+
for record in records:
|
| 134 |
+
output += (
|
| 135 |
+
f"Record ID: {record['Id']}\n"
|
| 136 |
+
f"Name: {record['Name']}\n"
|
| 137 |
+
f"Supervisor ID: {record['Supervisor_ID__c']}\n"
|
| 138 |
+
f"Project ID: {record['Project_ID__c']}\n"
|
| 139 |
+
f"Daily Checklist: {record['Daily_Checklist__c'] or 'N/A'}\n"
|
| 140 |
+
f"Suggested Tips: {record['Suggested_Tips__c'] or 'N/A'}\n"
|
| 141 |
+
f"Reflection Log: {record['Reflection_Log__c'] or 'N/A'}\n"
|
| 142 |
+
f"Engagement Score: {record['Engagement_Score__c'] or 0}%\n"
|
| 143 |
+
f"KPI Flag: {record['KPI_Flag__c']}\n"
|
| 144 |
+
f"Download Link: {record['Download_Link__c'] or 'N/A'}\n"
|
| 145 |
+
f"{'-'*50}\n"
|
| 146 |
+
)
|
| 147 |
+
return output, "", False
|
| 148 |
+
except Exception as e:
|
| 149 |
+
return f"Error querying Salesforce: {str(e)}", "", False
|
| 150 |
+
|
| 151 |
+
# Generate checklist from record
|
| 152 |
+
def gradio_generate_checklist(record_id, role="Supervisor", project_id="Unknown", project_name="Unknown Project", milestones="No milestones provided", supervisor_id="", project_id_sf="", reflection_log="", download_link=""):
|
| 153 |
+
try:
|
| 154 |
+
sf = get_salesforce_connection()
|
| 155 |
+
existing_record = sf.Supervisor_AI_Coaching__c.get(record_id, default={
|
| 156 |
+
'Name': '',
|
| 157 |
+
'Supervisor_ID__c': None,
|
| 158 |
+
'Project_ID__c': None,
|
| 159 |
+
'Reflection_Log__c': '',
|
| 160 |
+
'Download_Link__c': '',
|
| 161 |
+
'Engagement_Score__c': 0,
|
| 162 |
+
'KPI_Flag__c': False,
|
| 163 |
+
'Daily_Checklist__c': '',
|
| 164 |
+
'Suggested_Tips__c': ''
|
| 165 |
+
})
|
| 166 |
+
inputs = f"Role: {role} Project: {project_id} ({project_name}) Milestones: {milestones}"
|
| 167 |
+
input_ids = tokenizer(inputs, return_tensors="pt", max_length=128, truncation=True).input_ids
|
| 168 |
+
outputs = model.generate(input_ids, max_length=128, num_beams=4, early_stopping=True)
|
| 169 |
+
checklist = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 170 |
+
tips = "1. Prioritize safety checks\n2. Review milestones\n3. Log progress"
|
| 171 |
+
kpi_flag = "delay" in milestones.lower() or "behind" in milestones.lower()
|
| 172 |
+
|
| 173 |
+
update_data = {
|
| 174 |
+
'Daily_Checklist__c': checklist,
|
| 175 |
+
'Suggested_Tips__c': tips,
|
| 176 |
+
'Engagement_Score__c': existing_record.get('Engagement_Score__c', 0) + 10,
|
| 177 |
+
'KPI_Flag__c': kpi_flag,
|
| 178 |
+
'Supervisor_ID__c': supervisor_id if supervisor_id else existing_record.get('Supervisor_ID__c'),
|
| 179 |
+
'Project_ID__c': project_id_sf if project_id_sf else existing_record.get('Project_ID__c'),
|
| 180 |
+
'Reflection_Log__c': reflection_log if reflection_log else existing_record.get('Reflection_Log__c', ''),
|
| 181 |
+
'Download_Link__c': download_link if download_link else existing_record.get('Download_Link__c', '')
|
| 182 |
+
}
|
| 183 |
+
sf.Supervisor_AI_Coaching__c.update(record_id, update_data)
|
| 184 |
+
status = f"Updated Salesforce record {record_id}"
|
| 185 |
+
|
| 186 |
+
return checklist, tips, kpi_flag, status
|
| 187 |
+
except Exception as e:
|
| 188 |
+
return f"Error: {str(e)}", "", False, ""
|
| 189 |
+
|
| 190 |
+
# Define Gradio interface
|
| 191 |
+
with gr.Blocks() as iface:
|
| 192 |
+
gr.Markdown("# AI Coach for Site Supervisors")
|
| 193 |
+
gr.Markdown("Enter a Project ID to view Supervisor_AI_Coaching__c records and generate checklists.")
|
| 194 |
+
|
| 195 |
+
with gr.Tab("Login"):
|
| 196 |
+
project_id_input = gr.Textbox(label="Project ID (Salesforce Project__c ID)", placeholder="Enter Project ID")
|
| 197 |
+
login_button = gr.Button("Submit")
|
| 198 |
+
records_output = gr.Textbox(label="Records", lines=10)
|
| 199 |
+
login_button.click(
|
| 200 |
+
fn=login_and_display,
|
| 201 |
+
inputs=project_id_input,
|
| 202 |
+
outputs=[records_output, gr.Textbox(visible=False), gr.Checkbox(visible=False)]
|
| 203 |
+
)
|
| 204 |
+
|
| 205 |
+
with gr.Tab("Generate Checklist"):
|
| 206 |
+
record_id = gr.Textbox(label="Record ID", placeholder="Enter Record ID from above")
|
| 207 |
+
role = gr.Textbox(label="Role", value="Supervisor")
|
| 208 |
+
project_id = gr.Textbox(label="Project ID", value="P001")
|
| 209 |
+
project_name = gr.Textbox(label="Project Name", value="Building A")
|
| 210 |
+
milestones = gr.Textbox(label="Milestones", value="Complete foundation by 5/15")
|
| 211 |
+
supervisor_id = gr.Textbox(label="Supervisor ID (Salesforce User ID, optional)", value="")
|
| 212 |
+
project_id_sf = gr.Textbox(label="Project ID (Salesforce Project__c ID, optional)", value="")
|
| 213 |
+
reflection_log = gr.Textbox(label="Reflection Log (optional)", value="")
|
| 214 |
+
download_link = gr.Textbox(label="Download Link (optional)", value="")
|
| 215 |
+
generate_button = gr.Button("Generate and Update")
|
| 216 |
+
checklist_output = gr.Textbox(label="Checklist")
|
| 217 |
+
tips_output = gr.Textbox(label="Tips")
|
| 218 |
+
kpi_flag_output = gr.Checkbox(label="KPI Flag")
|
| 219 |
+
status_output = gr.Textbox(label="Salesforce Status")
|
| 220 |
+
generate_button.click(
|
| 221 |
+
fn=gradio_generate_checklist,
|
| 222 |
+
inputs=[record_id, role, project_id, project_name, milestones, supervisor_id, project_id_sf, reflection_log, download_link],
|
| 223 |
+
outputs=[checklist_output, tips_output, kpi_flag_output, status_output]
|
| 224 |
+
)
|
| 225 |
+
|
| 226 |
+
# Mount FastAPI
|
| 227 |
+
iface.app = app
|
| 228 |
+
|
| 229 |
+
if __name__ == "__main__":
|
| 230 |
+
try:
|
| 231 |
+
iface.launch(server_name="0.0.0.0", server_port=7860, share=False)
|
| 232 |
+
except Exception as e:
|
| 233 |
+
print(f"Failed to launch Gradio: {str(e)}")
|