Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -4,6 +4,10 @@ from transformers import AutoModelForCausalLM, AutoTokenizer
|
|
4 |
from simple_salesforce import Salesforce
|
5 |
import os
|
6 |
from dotenv import load_dotenv
|
|
|
|
|
|
|
|
|
7 |
|
8 |
# Load environment variables
|
9 |
load_dotenv()
|
@@ -14,7 +18,7 @@ missing_vars = [var for var in required_env_vars if not os.getenv(var)]
|
|
14 |
if missing_vars:
|
15 |
raise EnvironmentError(f"Missing required environment variables: {missing_vars}")
|
16 |
|
17 |
-
#
|
18 |
KPI_FLAG_DEFAULT = os.getenv('KPI_FLAG', 'True') == 'True'
|
19 |
ENGAGEMENT_SCORE_DEFAULT = float(os.getenv('ENGAGEMENT_SCORE', '85.0'))
|
20 |
|
@@ -111,18 +115,16 @@ def field_exists(sf, object_name, field_name):
|
|
111 |
print(f"⚠️ Error checking field {field_name}: {e}")
|
112 |
return False
|
113 |
|
114 |
-
#
|
115 |
def generate_salesforce_dashboard_url(supervisor_name, project_id):
|
116 |
-
# Use the provided Salesforce Visualforce URL with supervisorName and projectId as parameters
|
117 |
return f"https://aicoachforsitesupervisors-dev-ed--c.develop.vf.force.com/apex/DashboardPage?supervisorName={supervisor_name}&projectId={project_id}"
|
118 |
|
119 |
# Dashboard button function
|
120 |
def open_dashboard(role, supervisor_name, project_id):
|
121 |
-
# Generate dynamic URL based on supervisor and project
|
122 |
dashboard_url = generate_salesforce_dashboard_url(supervisor_name, project_id)
|
123 |
return f'<a href="{dashboard_url}" target="_blank" rel="noopener noreferrer" style="font-size:16px;">Open Salesforce Dashboard</a>'
|
124 |
|
125 |
-
#
|
126 |
def generate_outputs(role, supervisor_name, project_id, milestones, reflection):
|
127 |
if not all([role, supervisor_name, project_id, milestones, reflection]):
|
128 |
return "❗ Please fill all fields.", ""
|
@@ -156,11 +158,10 @@ def generate_outputs(role, supervisor_name, project_id, milestones, reflection):
|
|
156 |
e = text.find(end, s) if end else len(text)
|
157 |
return text[s + len(start):e].strip() if s != -1 else ""
|
158 |
|
159 |
-
# Extract the checklist and suggestions
|
160 |
checklist = extract_between(result, "Checklist:\n", "Suggestions:")
|
161 |
suggestions = extract_between(result, "Suggestions:\n", None)
|
162 |
|
163 |
-
#
|
164 |
if not checklist.strip():
|
165 |
checklist = generate_fallback_checklist(role, milestones)
|
166 |
if not suggestions.strip():
|
@@ -171,70 +172,105 @@ def generate_outputs(role, supervisor_name, project_id, milestones, reflection):
|
|
171 |
# Fallback generation for checklist and suggestions
|
172 |
def generate_fallback_checklist(role, milestones):
|
173 |
checklist_items = []
|
174 |
-
|
175 |
-
# If milestones are provided, add them to the checklist directly
|
176 |
-
if milestones and milestones.strip():
|
177 |
kpis = [kpi.strip() for kpi in milestones.split(",")]
|
178 |
for kpi in kpis:
|
179 |
checklist_items.append(f"- Ensure progress on {kpi}")
|
180 |
else:
|
181 |
checklist_items.append("- Perform daily safety inspection")
|
182 |
-
|
183 |
return "\n".join(checklist_items)
|
184 |
|
185 |
def generate_fallback_suggestions(reflection):
|
186 |
suggestions_items = []
|
187 |
reflection_lower = reflection.lower()
|
188 |
-
if "student" in reflection_lower or "learning" in reflection_lower:
|
189 |
-
suggestions_items.append("- Ensure students are logging incidents consistently")
|
190 |
-
suggestions_items.append("- Provide guidance on timely incident recording")
|
191 |
if "incident" in reflection_lower:
|
192 |
suggestions_items.append("- Follow up on reported incidents with corrective actions")
|
193 |
-
|
194 |
if not suggestions_items:
|
195 |
suggestions_items.append("- Monitor team coordination")
|
196 |
-
suggestions_items.append("- Review safety protocols with the team")
|
197 |
-
|
198 |
return "\n".join(suggestions_items)
|
199 |
|
200 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
201 |
def create_interface():
|
202 |
roles = get_roles_from_salesforce()
|
203 |
with gr.Blocks(theme="soft") as demo:
|
204 |
gr.Markdown("## 🧠 AI-Powered Supervisor Assistant")
|
205 |
-
|
206 |
with gr.Row():
|
207 |
role = gr.Dropdown(choices=roles, label="Role")
|
208 |
supervisor_name = gr.Dropdown(choices=[], label="Supervisor Name")
|
209 |
project_id = gr.Textbox(label="Project ID", interactive=False)
|
210 |
-
|
211 |
milestones = gr.Textbox(label="Milestones (comma-separated KPIs)", placeholder="E.g. Safety training, daily inspection")
|
212 |
reflection = gr.Textbox(label="Reflection Log", lines=4, placeholder="Any concerns, delays, updates...")
|
213 |
-
|
214 |
with gr.Row():
|
215 |
generate = gr.Button("Generate")
|
216 |
clear = gr.Button("Clear")
|
217 |
refresh = gr.Button("🔄 Refresh Roles")
|
218 |
dashboard_btn = gr.Button("Dashboard")
|
219 |
-
|
220 |
checklist_output = gr.Textbox(label="✅ Daily Checklist")
|
221 |
suggestions_output = gr.Textbox(label="💡 Focus Suggestions")
|
222 |
dashboard_link = gr.HTML("")
|
223 |
-
|
224 |
role.change(fn=lambda r: gr.update(choices=get_supervisor_name_by_role(r)), inputs=role, outputs=supervisor_name)
|
225 |
supervisor_name.change(fn=get_projects_for_supervisor, inputs=supervisor_name, outputs=project_id)
|
226 |
-
|
227 |
-
|
228 |
-
inputs=[role, supervisor_name, project_id, milestones, reflection],
|
229 |
-
outputs=[checklist_output, suggestions_output])
|
230 |
-
|
231 |
-
clear.click(fn=lambda: ("", "", "", "", ""), inputs=None,
|
232 |
-
outputs=[role, supervisor_name, project_id, milestones, reflection])
|
233 |
-
|
234 |
refresh.click(fn=lambda: gr.update(choices=get_roles_from_salesforce()), outputs=role)
|
235 |
-
|
236 |
dashboard_btn.click(fn=open_dashboard, inputs=[role, supervisor_name, project_id], outputs=dashboard_link)
|
237 |
-
|
238 |
return demo
|
239 |
|
240 |
if __name__ == "__main__":
|
|
|
4 |
from simple_salesforce import Salesforce
|
5 |
import os
|
6 |
from dotenv import load_dotenv
|
7 |
+
import pandas as pd
|
8 |
+
from reportlab.lib.pagesizes import letter
|
9 |
+
from reportlab.pdfgen import canvas
|
10 |
+
from io import BytesIO
|
11 |
|
12 |
# Load environment variables
|
13 |
load_dotenv()
|
|
|
18 |
if missing_vars:
|
19 |
raise EnvironmentError(f"Missing required environment variables: {missing_vars}")
|
20 |
|
21 |
+
# Default settings
|
22 |
KPI_FLAG_DEFAULT = os.getenv('KPI_FLAG', 'True') == 'True'
|
23 |
ENGAGEMENT_SCORE_DEFAULT = float(os.getenv('ENGAGEMENT_SCORE', '85.0'))
|
24 |
|
|
|
115 |
print(f"⚠️ Error checking field {field_name}: {e}")
|
116 |
return False
|
117 |
|
118 |
+
# Function to generate Salesforce dashboard URL (Visualforce Page)
|
119 |
def generate_salesforce_dashboard_url(supervisor_name, project_id):
|
|
|
120 |
return f"https://aicoachforsitesupervisors-dev-ed--c.develop.vf.force.com/apex/DashboardPage?supervisorName={supervisor_name}&projectId={project_id}"
|
121 |
|
122 |
# Dashboard button function
|
123 |
def open_dashboard(role, supervisor_name, project_id):
|
|
|
124 |
dashboard_url = generate_salesforce_dashboard_url(supervisor_name, project_id)
|
125 |
return f'<a href="{dashboard_url}" target="_blank" rel="noopener noreferrer" style="font-size:16px;">Open Salesforce Dashboard</a>'
|
126 |
|
127 |
+
# Function to generate daily checklist and suggestions
|
128 |
def generate_outputs(role, supervisor_name, project_id, milestones, reflection):
|
129 |
if not all([role, supervisor_name, project_id, milestones, reflection]):
|
130 |
return "❗ Please fill all fields.", ""
|
|
|
158 |
e = text.find(end, s) if end else len(text)
|
159 |
return text[s + len(start):e].strip() if s != -1 else ""
|
160 |
|
|
|
161 |
checklist = extract_between(result, "Checklist:\n", "Suggestions:")
|
162 |
suggestions = extract_between(result, "Suggestions:\n", None)
|
163 |
|
164 |
+
# Fallback generation
|
165 |
if not checklist.strip():
|
166 |
checklist = generate_fallback_checklist(role, milestones)
|
167 |
if not suggestions.strip():
|
|
|
172 |
# Fallback generation for checklist and suggestions
|
173 |
def generate_fallback_checklist(role, milestones):
|
174 |
checklist_items = []
|
175 |
+
if milestones:
|
|
|
|
|
176 |
kpis = [kpi.strip() for kpi in milestones.split(",")]
|
177 |
for kpi in kpis:
|
178 |
checklist_items.append(f"- Ensure progress on {kpi}")
|
179 |
else:
|
180 |
checklist_items.append("- Perform daily safety inspection")
|
|
|
181 |
return "\n".join(checklist_items)
|
182 |
|
183 |
def generate_fallback_suggestions(reflection):
|
184 |
suggestions_items = []
|
185 |
reflection_lower = reflection.lower()
|
|
|
|
|
|
|
186 |
if "incident" in reflection_lower:
|
187 |
suggestions_items.append("- Follow up on reported incidents with corrective actions")
|
|
|
188 |
if not suggestions_items:
|
189 |
suggestions_items.append("- Monitor team coordination")
|
|
|
|
|
190 |
return "\n".join(suggestions_items)
|
191 |
|
192 |
+
# Function to generate a PDF report
|
193 |
+
def generate_pdf_report(supervisor_name, project_id, checklist, suggestions):
|
194 |
+
file_path = f"reports/{supervisor_name}_{project_id}_report.pdf"
|
195 |
+
buffer = BytesIO()
|
196 |
+
c = canvas.Canvas(buffer, pagesize=letter)
|
197 |
+
c.drawString(100, 750, f"Supervisor: {supervisor_name}")
|
198 |
+
c.drawString(100, 735, f"Project ID: {project_id}")
|
199 |
+
c.drawString(100, 700, "Daily Checklist:")
|
200 |
+
y_position = 685
|
201 |
+
for task in checklist.splitlines():
|
202 |
+
c.drawString(100, y_position, f"- {task}")
|
203 |
+
y_position -= 15
|
204 |
+
c.drawString(100, y_position - 20, "Focus Suggestions:")
|
205 |
+
y_position -= 40
|
206 |
+
for suggestion in suggestions.splitlines():
|
207 |
+
c.drawString(100, y_position, f"- {suggestion}")
|
208 |
+
y_position -= 15
|
209 |
+
c.showPage()
|
210 |
+
c.save()
|
211 |
+
buffer.seek(0)
|
212 |
+
with open(file_path, 'wb') as f:
|
213 |
+
f.write(buffer.read())
|
214 |
+
return file_path
|
215 |
+
|
216 |
+
# Function to generate a CSV report
|
217 |
+
def generate_csv_report(supervisor_name, project_id, checklist, suggestions):
|
218 |
+
file_path = f"reports/{supervisor_name}_{project_id}_report.csv"
|
219 |
+
data = {
|
220 |
+
"Supervisor": [supervisor_name],
|
221 |
+
"Project ID": [project_id],
|
222 |
+
"Checklist": [checklist],
|
223 |
+
"Suggestions": [suggestions]
|
224 |
+
}
|
225 |
+
df = pd.DataFrame(data)
|
226 |
+
df.to_csv(file_path, index=False)
|
227 |
+
return file_path
|
228 |
+
|
229 |
+
# Function to store the download link in Salesforce
|
230 |
+
def store_download_link_in_salesforce(supervisor_name, download_link):
|
231 |
+
try:
|
232 |
+
sf = Salesforce(
|
233 |
+
username=os.getenv('SF_USERNAME'),
|
234 |
+
password=os.getenv('SF_PASSWORD'),
|
235 |
+
security_token=os.getenv('SF_SECURITY_TOKEN'),
|
236 |
+
domain=os.getenv('SF_DOMAIN', 'login')
|
237 |
+
)
|
238 |
+
result = sf.query(f"SELECT Id FROM Supervisor_AI_Coaching__c WHERE Supervisor_Name__c = '{supervisor_name}' LIMIT 1")
|
239 |
+
if result['totalSize'] == 0:
|
240 |
+
return "Supervisor not found."
|
241 |
+
supervisor_ai_coaching_id = result['records'][0]['Id']
|
242 |
+
sf.Supervisor_AI_Coaching__c.update(supervisor_ai_coaching_id, {
|
243 |
+
'Download_Link__c': download_link
|
244 |
+
})
|
245 |
+
return "Download link stored successfully."
|
246 |
+
except Exception as e:
|
247 |
+
return f"Error storing download link: {e}"
|
248 |
+
|
249 |
+
# Interface function
|
250 |
def create_interface():
|
251 |
roles = get_roles_from_salesforce()
|
252 |
with gr.Blocks(theme="soft") as demo:
|
253 |
gr.Markdown("## 🧠 AI-Powered Supervisor Assistant")
|
|
|
254 |
with gr.Row():
|
255 |
role = gr.Dropdown(choices=roles, label="Role")
|
256 |
supervisor_name = gr.Dropdown(choices=[], label="Supervisor Name")
|
257 |
project_id = gr.Textbox(label="Project ID", interactive=False)
|
|
|
258 |
milestones = gr.Textbox(label="Milestones (comma-separated KPIs)", placeholder="E.g. Safety training, daily inspection")
|
259 |
reflection = gr.Textbox(label="Reflection Log", lines=4, placeholder="Any concerns, delays, updates...")
|
|
|
260 |
with gr.Row():
|
261 |
generate = gr.Button("Generate")
|
262 |
clear = gr.Button("Clear")
|
263 |
refresh = gr.Button("🔄 Refresh Roles")
|
264 |
dashboard_btn = gr.Button("Dashboard")
|
|
|
265 |
checklist_output = gr.Textbox(label="✅ Daily Checklist")
|
266 |
suggestions_output = gr.Textbox(label="💡 Focus Suggestions")
|
267 |
dashboard_link = gr.HTML("")
|
|
|
268 |
role.change(fn=lambda r: gr.update(choices=get_supervisor_name_by_role(r)), inputs=role, outputs=supervisor_name)
|
269 |
supervisor_name.change(fn=get_projects_for_supervisor, inputs=supervisor_name, outputs=project_id)
|
270 |
+
generate.click(fn=generate_outputs, inputs=[role, supervisor_name, project_id, milestones, reflection], outputs=[checklist_output, suggestions_output])
|
271 |
+
clear.click(fn=lambda: ("", "", "", "", ""), inputs=None, outputs=[role, supervisor_name, project_id, milestones, reflection])
|
|
|
|
|
|
|
|
|
|
|
|
|
272 |
refresh.click(fn=lambda: gr.update(choices=get_roles_from_salesforce()), outputs=role)
|
|
|
273 |
dashboard_btn.click(fn=open_dashboard, inputs=[role, supervisor_name, project_id], outputs=dashboard_link)
|
|
|
274 |
return demo
|
275 |
|
276 |
if __name__ == "__main__":
|