Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,9 +1,10 @@
|
|
1 |
import gradio as gr
|
2 |
-
import torch
|
3 |
-
from transformers import AutoModelForCausalLM, AutoTokenizer
|
4 |
-
from simple_salesforce import Salesforce
|
5 |
import os
|
6 |
-
from
|
|
|
|
|
|
|
|
|
7 |
|
8 |
# Load environment variables
|
9 |
load_dotenv()
|
@@ -14,187 +15,115 @@ 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 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
model_name = "distilgpt2" # Using distilgpt2 for faster response
|
23 |
-
tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=True)
|
24 |
-
model = AutoModelForCausalLM.from_pretrained(model_name, low_cpu_mem_usage=True)
|
25 |
-
|
26 |
-
if tokenizer.pad_token is None:
|
27 |
-
tokenizer.pad_token = tokenizer.eos_token
|
28 |
-
tokenizer.pad_token_id = tokenizer.convert_tokens_to_ids(tokenizer.pad_token)
|
29 |
-
model.config.pad_token_id = tokenizer.pad_token_id
|
30 |
-
|
31 |
-
# Refined Prompt to generate day-by-day tasks based on milestones
|
32 |
-
PROMPT_TEMPLATE = """You are an AI assistant for construction supervisors. Given the role, project, milestones, and a reflection log, generate:
|
33 |
-
|
34 |
-
1. A Daily Checklist with clear and concise tasks based on the role and milestones.
|
35 |
-
Split the checklist into day-by-day tasks for a specified time period (e.g., one week).
|
36 |
-
2. Focus Suggestions based on concerns or keywords in the reflection log. Provide at least 2 suggestions.
|
37 |
-
|
38 |
-
Inputs:
|
39 |
-
Role: {role}
|
40 |
-
Project ID: {project_id}
|
41 |
-
Milestones: {milestones}
|
42 |
-
Reflection Log: {reflection}
|
43 |
-
|
44 |
-
Output Format:
|
45 |
-
Checklist (Day-by-Day):
|
46 |
-
- Day 1:
|
47 |
-
- Task 1
|
48 |
-
- Task 2
|
49 |
-
- Day 2:
|
50 |
-
- Task 1
|
51 |
-
- Task 2
|
52 |
-
...
|
53 |
-
Suggestions:
|
54 |
-
-
|
55 |
-
"""
|
56 |
-
|
57 |
-
# Salesforce Functions
|
58 |
-
def get_roles_from_salesforce():
|
59 |
-
try:
|
60 |
-
sf = Salesforce(
|
61 |
-
username=os.getenv('SF_USERNAME'),
|
62 |
-
password=os.getenv('SF_PASSWORD'),
|
63 |
-
security_token=os.getenv('SF_SECURITY_TOKEN'),
|
64 |
-
domain=os.getenv('SF_DOMAIN', 'login')
|
65 |
-
)
|
66 |
-
result = sf.query("SELECT Role__c FROM Supervisor__c WHERE Role__c != NULL")
|
67 |
-
return list(set(record['Role__c'] for record in result['records']))
|
68 |
-
except Exception as e:
|
69 |
-
print(f"⚠️ Error fetching roles: {e}")
|
70 |
-
return ["Site Manager", "Safety Officer", "Project Lead"]
|
71 |
|
72 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
73 |
try:
|
74 |
sf = Salesforce(
|
75 |
-
username=
|
76 |
-
password=
|
77 |
-
security_token=
|
78 |
-
domain=
|
79 |
)
|
80 |
-
|
81 |
-
result = sf.query(f"SELECT
|
82 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
83 |
except Exception as e:
|
84 |
-
|
85 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
86 |
|
87 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
88 |
try:
|
89 |
sf = Salesforce(
|
90 |
-
username=
|
91 |
-
password=
|
92 |
-
security_token=
|
93 |
-
domain=
|
94 |
)
|
95 |
-
|
96 |
-
|
97 |
-
if supervisor_result['totalSize'] == 0:
|
98 |
-
return ""
|
99 |
-
supervisor_id = supervisor_result['records'][0]['Id']
|
100 |
-
project_result = sf.query(f"SELECT Name FROM Project__c WHERE Supervisor_ID__c = '{supervisor_id}' LIMIT 1")
|
101 |
-
return project_result['records'][0]['Name'] if project_result['totalSize'] > 0 else ""
|
102 |
-
except Exception as e:
|
103 |
-
print(f"⚠️ Error fetching project: {e}")
|
104 |
-
return ""
|
105 |
-
|
106 |
-
def generate_salesforce_dashboard_url(supervisor_name, project_id):
|
107 |
-
# Use the provided Salesforce Visualforce URL with supervisorName and projectId as parameters
|
108 |
-
return f"https://aicoachforsitesupervisors-dev-ed--c.develop.vf.force.com/apex/DashboardPage?supervisorName={supervisor_name}&projectId={project_id}"
|
109 |
-
|
110 |
-
def generate_salesforce_report_url(supervisor_name, project_id):
|
111 |
-
# Similar function to generate a report URL for supervisor and project
|
112 |
-
return f"https://aicoachforsitesupervisors-dev-ed--c.develop.vf.force.com/apex/ReportPage?supervisorName={supervisor_name}&projectId={project_id}"
|
113 |
-
|
114 |
-
# Function to open the dashboard page
|
115 |
-
def open_dashboard(role, supervisor_name, project_id):
|
116 |
-
dashboard_url = generate_salesforce_dashboard_url(supervisor_name, project_id)
|
117 |
-
return f'<a href="{dashboard_url}" target="_blank" rel="noopener noreferrer" style="font-size:16px;">Open Salesforce Dashboard</a>'
|
118 |
-
|
119 |
-
# Function to open the report page
|
120 |
-
def open_report_page(role, supervisor_name, project_id):
|
121 |
-
report_url = generate_salesforce_report_url(supervisor_name, project_id)
|
122 |
-
return f'<a href="{report_url}" target="_blank" rel="noopener noreferrer" style="font-size:16px;">Open Supervisor Report</a>'
|
123 |
-
|
124 |
-
# Generate function
|
125 |
-
def generate_outputs(role, supervisor_name, project_id, milestones, reflection):
|
126 |
-
if not all([role, supervisor_name, project_id, milestones, reflection]):
|
127 |
-
return "❗ Please fill all fields.", ""
|
128 |
-
|
129 |
-
prompt = PROMPT_TEMPLATE.format(
|
130 |
-
role=role,
|
131 |
-
project_id=project_id,
|
132 |
-
milestones=milestones,
|
133 |
-
reflection=reflection
|
134 |
-
)
|
135 |
-
|
136 |
-
inputs = tokenizer(prompt, return_tensors="pt", padding=True, truncation=True, max_length=512)
|
137 |
-
try:
|
138 |
-
with torch.no_grad():
|
139 |
-
outputs = model.generate(
|
140 |
-
inputs['input_ids'],
|
141 |
-
max_new_tokens=150, # Increased max tokens to capture more content
|
142 |
-
no_repeat_ngram_size=2,
|
143 |
-
do_sample=True,
|
144 |
-
top_p=0.9,
|
145 |
-
temperature=0.7,
|
146 |
-
pad_token_id=tokenizer.pad_token_id
|
147 |
-
)
|
148 |
-
result = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
149 |
except Exception as e:
|
150 |
-
print(f"⚠️
|
151 |
-
return "", ""
|
152 |
-
|
153 |
-
def extract_between(text, start, end):
|
154 |
-
s = text.find(start)
|
155 |
-
e = text.find(end, s) if end else len(text)
|
156 |
-
return text[s + len(start):e].strip() if s != -1 else ""
|
157 |
-
|
158 |
-
# Extract the checklist and suggestions
|
159 |
-
checklist = extract_between(result, "Checklist:\n", "Suggestions:")
|
160 |
-
suggestions = extract_between(result, "Suggestions:\n", None)
|
161 |
-
|
162 |
-
# If checklist or suggestions are empty, generate fallback content
|
163 |
-
if not checklist.strip():
|
164 |
-
checklist = generate_fallback_checklist(role, milestones)
|
165 |
-
if not suggestions.strip():
|
166 |
-
suggestions = generate_fallback_suggestions(reflection)
|
167 |
-
|
168 |
-
return checklist, suggestions
|
169 |
-
|
170 |
-
# Fallback generation for checklist and suggestions
|
171 |
-
def generate_fallback_checklist(role, milestones):
|
172 |
-
checklist_items = []
|
173 |
-
|
174 |
-
# If milestones are provided, add them to the checklist directly
|
175 |
-
if milestones and milestones.strip():
|
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 |
-
|
182 |
-
return "\n".join(checklist_items)
|
183 |
-
|
184 |
-
def generate_fallback_suggestions(reflection):
|
185 |
-
suggestions_items = []
|
186 |
-
reflection_lower = reflection.lower()
|
187 |
-
if "student" in reflection_lower or "learning" in reflection_lower:
|
188 |
-
suggestions_items.append("- Ensure students are logging incidents consistently")
|
189 |
-
suggestions_items.append("- Provide guidance on timely incident recording")
|
190 |
-
if "incident" in reflection_lower:
|
191 |
-
suggestions_items.append("- Follow up on reported incidents with corrective actions")
|
192 |
-
|
193 |
-
if not suggestions_items:
|
194 |
-
suggestions_items.append("- Monitor team coordination")
|
195 |
-
suggestions_items.append("- Review safety protocols with the team")
|
196 |
-
|
197 |
-
return "\n".join(suggestions_items)
|
198 |
|
199 |
# Interface
|
200 |
def create_interface():
|
@@ -215,7 +144,7 @@ def create_interface():
|
|
215 |
clear = gr.Button("Clear")
|
216 |
refresh = gr.Button("🔄 Refresh Roles")
|
217 |
dashboard_btn = gr.Button("Dashboard")
|
218 |
-
report_btn = gr.Button("Report")
|
219 |
|
220 |
checklist_output = gr.Textbox(label="✅ Daily Checklist")
|
221 |
suggestions_output = gr.Textbox(label="💡 Focus Suggestions")
|
@@ -235,7 +164,10 @@ def create_interface():
|
|
235 |
refresh.click(fn=lambda: gr.update(choices=get_roles_from_salesforce()), outputs=role)
|
236 |
|
237 |
dashboard_btn.click(fn=open_dashboard, inputs=[role, supervisor_name, project_id], outputs=dashboard_link)
|
238 |
-
|
|
|
|
|
|
|
239 |
|
240 |
return demo
|
241 |
|
|
|
1 |
import gradio as gr
|
|
|
|
|
|
|
2 |
import os
|
3 |
+
from simple_salesforce import Salesforce
|
4 |
+
import pandas as pd
|
5 |
+
from reportlab.lib.pagesizes import letter
|
6 |
+
from reportlab.pdfgen import canvas
|
7 |
+
from io import BytesIO
|
8 |
|
9 |
# Load environment variables
|
10 |
load_dotenv()
|
|
|
15 |
if missing_vars:
|
16 |
raise EnvironmentError(f"Missing required environment variables: {missing_vars}")
|
17 |
|
18 |
+
# Salesforce credentials
|
19 |
+
SF_USERNAME = os.getenv('SF_USERNAME')
|
20 |
+
SF_PASSWORD = os.getenv('SF_PASSWORD')
|
21 |
+
SF_SECURITY_TOKEN = os.getenv('SF_SECURITY_TOKEN')
|
22 |
+
SF_DOMAIN = os.getenv('SF_DOMAIN', 'login')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
23 |
|
24 |
+
# Function to generate a PDF report for the supervisor
|
25 |
+
def generate_pdf_report(supervisor_name, project_id, checklist, suggestions):
|
26 |
+
file_path = f"reports/{supervisor_name}_{project_id}_report.pdf"
|
27 |
+
|
28 |
+
buffer = BytesIO()
|
29 |
+
c = canvas.Canvas(buffer, pagesize=letter)
|
30 |
+
c.drawString(100, 750, f"Supervisor: {supervisor_name}")
|
31 |
+
c.drawString(100, 735, f"Project ID: {project_id}")
|
32 |
+
|
33 |
+
c.drawString(100, 700, "Daily Checklist:")
|
34 |
+
y_position = 685
|
35 |
+
for task in checklist.splitlines():
|
36 |
+
c.drawString(100, y_position, f"- {task}")
|
37 |
+
y_position -= 15
|
38 |
+
|
39 |
+
c.drawString(100, y_position - 20, "Focus Suggestions:")
|
40 |
+
y_position -= 40
|
41 |
+
for suggestion in suggestions.splitlines():
|
42 |
+
c.drawString(100, y_position, f"- {suggestion}")
|
43 |
+
y_position -= 15
|
44 |
+
|
45 |
+
c.showPage()
|
46 |
+
c.save()
|
47 |
+
buffer.seek(0)
|
48 |
+
|
49 |
+
with open(file_path, 'wb') as f:
|
50 |
+
f.write(buffer.read())
|
51 |
+
|
52 |
+
return file_path
|
53 |
+
|
54 |
+
# Function to generate CSV report
|
55 |
+
def generate_csv_report(supervisor_name, project_id, checklist, suggestions):
|
56 |
+
file_path = f"reports/{supervisor_name}_{project_id}_report.csv"
|
57 |
+
|
58 |
+
data = {
|
59 |
+
"Supervisor": [supervisor_name],
|
60 |
+
"Project ID": [project_id],
|
61 |
+
"Checklist": [checklist],
|
62 |
+
"Suggestions": [suggestions]
|
63 |
+
}
|
64 |
+
|
65 |
+
df = pd.DataFrame(data)
|
66 |
+
df.to_csv(file_path, index=False)
|
67 |
+
|
68 |
+
return file_path
|
69 |
+
|
70 |
+
# Function to store the download link in Salesforce
|
71 |
+
def store_download_link_in_salesforce(supervisor_name, download_link):
|
72 |
try:
|
73 |
sf = Salesforce(
|
74 |
+
username=SF_USERNAME,
|
75 |
+
password=SF_PASSWORD,
|
76 |
+
security_token=SF_SECURITY_TOKEN,
|
77 |
+
domain=SF_DOMAIN
|
78 |
)
|
79 |
+
# Query for the supervisor record in the Supervisor_AI_Coaching__c object
|
80 |
+
result = sf.query(f"SELECT Id FROM Supervisor_AI_Coaching__c WHERE Supervisor_Name__c = '{supervisor_name}' LIMIT 1")
|
81 |
+
|
82 |
+
if result['totalSize'] == 0:
|
83 |
+
return "Supervisor not found."
|
84 |
+
|
85 |
+
supervisor_ai_coaching_id = result['records'][0]['Id']
|
86 |
+
|
87 |
+
# Update the record with the download link in the Download_Link__c field
|
88 |
+
sf.Supervisor_AI_Coaching__c.update(supervisor_ai_coaching_id, {
|
89 |
+
'Download_Link__c': download_link # Assuming 'Download_Link__c' is the custom field for storing the link
|
90 |
+
})
|
91 |
+
|
92 |
+
return "Download link stored successfully."
|
93 |
+
|
94 |
except Exception as e:
|
95 |
+
return f"Error storing download link: {e}"
|
96 |
+
|
97 |
+
# Function to generate the report, provide the link, and store it in Salesforce
|
98 |
+
def generate_and_store_report(role, supervisor_name, project_id, checklist, suggestions, report_type="PDF"):
|
99 |
+
# Generate the report
|
100 |
+
if report_type == "PDF":
|
101 |
+
report_path = generate_pdf_report(supervisor_name, project_id, checklist, suggestions)
|
102 |
+
else:
|
103 |
+
report_path = generate_csv_report(supervisor_name, project_id, checklist, suggestions)
|
104 |
|
105 |
+
# Create a download link
|
106 |
+
download_link = f"/static/{report_path}" # Assuming the app is set up to serve static files from the 'static' directory
|
107 |
+
|
108 |
+
# Store the download link in Salesforce
|
109 |
+
result = store_download_link_in_salesforce(supervisor_name, download_link)
|
110 |
+
|
111 |
+
return download_link, result
|
112 |
+
|
113 |
+
# Function to get roles from Salesforce
|
114 |
+
def get_roles_from_salesforce():
|
115 |
try:
|
116 |
sf = Salesforce(
|
117 |
+
username=SF_USERNAME,
|
118 |
+
password=SF_PASSWORD,
|
119 |
+
security_token=SF_SECURITY_TOKEN,
|
120 |
+
domain=SF_DOMAIN
|
121 |
)
|
122 |
+
result = sf.query("SELECT Role__c FROM Supervisor__c WHERE Role__c != NULL")
|
123 |
+
return list(set(record['Role__c'] for record in result['records']))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
124 |
except Exception as e:
|
125 |
+
print(f"⚠️ Error fetching roles: {e}")
|
126 |
+
return ["Site Manager", "Safety Officer", "Project Lead"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
127 |
|
128 |
# Interface
|
129 |
def create_interface():
|
|
|
144 |
clear = gr.Button("Clear")
|
145 |
refresh = gr.Button("🔄 Refresh Roles")
|
146 |
dashboard_btn = gr.Button("Dashboard")
|
147 |
+
report_btn = gr.Button("Download Report")
|
148 |
|
149 |
checklist_output = gr.Textbox(label="✅ Daily Checklist")
|
150 |
suggestions_output = gr.Textbox(label="💡 Focus Suggestions")
|
|
|
164 |
refresh.click(fn=lambda: gr.update(choices=get_roles_from_salesforce()), outputs=role)
|
165 |
|
166 |
dashboard_btn.click(fn=open_dashboard, inputs=[role, supervisor_name, project_id], outputs=dashboard_link)
|
167 |
+
|
168 |
+
report_btn.click(fn=generate_and_store_report,
|
169 |
+
inputs=[role, supervisor_name, project_id, checklist_output, suggestions_output],
|
170 |
+
outputs=[report_link, gr.HTML("")])
|
171 |
|
172 |
return demo
|
173 |
|